Graphics & Images

Outline:


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 ()


(end)