Graphics & Images

Outline:


Simple Image

from PIL import Image

s = "CA"
Image.open ("flowers/" + s + ".jpg").show()

print ("Bye")

Alternative using matplotlib:

import matplotlib.image as mpimg
from matplotlib import pyplot
img = mpimg.imread("flowers/" + s + ".jpg")
p
yplot.close () # fighting with other images?
pyplot.title (f'Bar graph for {n} states') # set some title
pyplot
.imshow(img)
pyplot.pause (0.1) # will NOT block continuation of program
pyplot.show() # will block until graphic closed


Bar charts rolling dice

import random
import matplotlib
from matplotlib import pyplot as plt
import numpy as np

# def rolla (n):
# f = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
# for g in range (n):
# k = random.randrange(1,7)
# f.update({k:f.get (k)+1})
# return f

# h = rolla (2000)
# print (h)
# print (str(h).replace (", ", "\n")
# .replace ("{" , "")
# .replace ("}" , ""))
# print (list(h.keys()))
# plt.bar (list(h.keys()), list(h.values()))


rolls = [random.randrange(1,7) for i in range (2000)]
values, freqs = np.unique(rolls, return_counts=True)
print (values, freqs)
plt.bar(values, freqs)
# matplotlib.pyplot.show()

plt.savefig ("v01.png")

Graphics in v01.png
v01.png


Titanic example:

# titanic01.py
import pandas as pd

tc = pd.read_csv ('TitanicSurvival.csv')
# print (tc)

def check (col, rx, sn):
   b = tc[col].str.match (r'('+rx+')')
   if b.size > 0:
      b = b.fillna (True)
      b = tc[b].fillna (-1)
#       b = tc[b].fillna ("<missing>")
#       print ("\nThe following lines have "+sn)
      print ("Number of "+sn+":\n", b.count(), sep="")
   else:
      print ("\nAll "+sn+"s are ok.")
   return b

x = check ('sex' , 'male'           , 'males')
# print (x)
print (x.describe())
# print ("\nSurvived:\n", (tc.survived == 'yes').describe(), sep='')
# print ("\n1st class:\n", (tc.passengerClass == '1st').describe(), sep='')
# print ("\n1st class & survived:\n", ((tc.passengerClass == '1st') & (tc.survived == 'yes')).describe(), sep='')
# print ("\n3rd class & survived:\n", (tc[(tc['passengerClass'] == '3rd') & (tc['survived'] == 'yes')]), sep='')
# print ("\n3rd class & died:\n", (tc[(tc['passengerClass'] == '3rd') & (tc['survived'] == 'no')]), sep='')
# print ("\n3rd class:\n", (tc.passengerClass == '3rd').describe(), sep='')

import matplotlib
from matplotlib import pyplot as plt
hist = x.hist(bins=[-10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

# following does not continue until plot is closed
matplotlib.pyplot.show()


s = str (plt.gcf().canvas.get_supported_filetypes())
s = s.replace (", ", "\n").replace ("{", "")
print ("\nSupported formats:\n" + s + "\n")
plt.savefig ("v01.png")
plt.savefig ("v01.svg")


Output:

Number of males:
name              843
survived          843
sex               843
age               843
passengerClass    843
dtype: int64
              age
count  843.000000
mean    23.653717
std     18.171896
min     -1.000000
25%      4.000000
50%     24.500000
75%     35.000000
max     80.000000


Images - Flask

It looks like the way to make this work is by putting images in a "static" folder, under the current python source code.

Code:
# w6_03.py

s1 = """
<html>
  <head>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>See the fly</title>
  </head>
  <body>
    <h1>Is this fun or what? - 4</h1>
    <img src="/static/fly.jpg" alt="The image of a fly">
  </body>
</html>
"""

from flask import Flask

app = Flask(__name__)

@app.route('/')

def helloIndex():
   return s1

# standard run host server command:  
app.run(host='0.0.0.0', port= 8080)



Non-blocking code:

As part of showing an image, use pause rather than show, and clf to clean up the figure from previous plot.
plt.clf() # ND
plt.imshow(image)
plt.pause (.1) # show() # ND
or
plt.clf() # ND
plt.bar(nameList, valueList, color='green', width=0.4)
plt.xlabel("Names")
plt.ylabel("Values")
plt.title("Title")
plt.pause (0.1) # show() # ND

Pandas

Sorting, selecting and removing n extreme values, some histogram options
from matplotlib import pyplot as plt

pop   = pd.read_csv ("PopChange.csv")

col = 'Pop Jul 1'
x = pop [col]
# type of x is <class 'pandas.core.series.Series'>
# so operations on x are from pandas on Series

# remove n values:
n = 2

x = x.sort_values (ascending=False)
print ("Removed:\n", x.iloc[0: n])
x = x.iloc[n:]

print (x.describe())

# various pre-defined bin systems:
v = "auto"

# v = "fd"
# v = "doane"
# v = "scott"
# v = "stone"
# v = "rice"
# v = "sturges"
# v = "sqrt"

hist = x.hist(bins=v, log=True)
plt.title (col + ': ' + v)
plt.show ()
Other useful options in plotting Pandas or other plots:

Rolling Dice Animation

# v056.py
# D&D 6.4.2 - dynamic visualization
# animation of rolling dice graph
# added possiblity of multiple dice
# use dictionary rather than list

from matplotlib import animation
import matplotlib.pyplot as plt
import random
import seaborn as sns

nod = 5 # number of dice
nos = 10 # number of sides on a die

nof = 30 # number of frames
rpf = 100 # number of rolls per frame

labelBars = False
animateMe = False

sns.set_style ('whitegrid')

figure = plt.figure ('Rolling dice')

def dieTotal (n):
   v = 0;
   for i in range (0,n):
      v += random.randrange (1, nos + 1)
   return v

def update (frame_number, rolls, frequencies):
  for i in range (rolls):
    frequencies [dieTotal(nod)] += 1
  plt.cla()
  ux = list(frequencies.keys())
  uy = list(frequencies.values())
  axes = sns.barplot (x=ux, y=uy, palette='bright')
  axes.set_title (f'Die Total Frequencies of {nod} {nos}-sided dice for {sum(frequencies.values()):,} Rolls')
  axes.set (xlabel='Die Value', ylabel='Frequency')
  axes.set_ylim (top=max (uy) * 1.10)
  if labelBars:
     for bar, frequency in zip (axes.patches, uy):
       text_x = bar.get_x() + bar.get_width()/2.0
       text_y = bar.get_height()
       text = f'{frequency:,}\n{frequency / sum (frequencies):.1%}'
       if frequency == 0: text = ''
       axes.text (text_x, text_y, text, ha='center', va='bottom')
  if frame_number == nof-1:
    print (f'Frame number: {frame_number}\n{frequencies}\n')

frequencies = {}
for i in range (nod, nod*nos+1): frequencies [i] = 0

if animateMe:
   die_animation = animation.FuncAnimation (
     figure, update, repeat=False, frames = nof, interval=33,
     fargs=(rpf, frequencies))
else:
   update (nof-1, rpf*nof, frequencies)
 
plt.show()


Formatting y axis

    population_values = []
    state_names = []
    for place in keys:
        population_values += [STATES[place]['Population']]
#         population_values += ["{:,}".format(STATES[place]['Population'])]
        state_names += [place]

    # Creating the bar plot
    fig, ax = plt.subplots ()
    plt.bar(state_names, population_values, width = 0.8)
    ax.yaxis.set_major_formatter (lambda x, p: f'{x/1000000:,.0f}M - {p}')
    plt.title("BAR GRAPH OF THE TOP 5 POPULATED STATES")
    plt.xlabel("STATES")
    plt.ylabel("POPULATION")
    plt.show()


(end)