Python Examples - PyPlot

+====================================================================+ | Use pip to display the current version of matplotlib installed | | (There have been many change from older versions) | +====================================================================+ pip list or pip show matplotlib or pip show matplotlib | grep Verson

+====================================================================+ | Use Python to display the current version of matplotlib installed | | (There have been many change from older versions) | +====================================================================+ import matplotlib print(matplotlib.__version__)

#!/usr/bin/python3 # ==================================================================== # simple plot (1/X) # ==================================================================== import matplotlib.pyplot as plt # -------------------------------------------------------------------- # ---- get y coordinate value # -------------------------------------------------------------------- def y_value(x): return 1/x # -------------------------------------------------------------------- # ---- main # -------------------------------------------------------------------- # ---- initialize plot plt.title('plot 1/X') plt.xlabel('x') plt.ylabel('y') plt.grid(True) # ---- x coordinates (you can also use numpy.linspace()) x_coords = range(1,101) # ---- y coordinates y_coords = [] for x in x_coords: y_coords.append(y_value(x)) # ---- plot x,y plt.plot(x_coords,y_coords,color='red',linewidth=1.0) plt.show()

#!/usr/bin/python3 # ==================================================================== # line and scatter plot of randomly generated data # ==================================================================== import random import matplotlib.pyplot as plt b = 3 # line y-intercept m = .5 # line slope rangemin = -20 # x coord min rangemax = 20 # y coord max # ---- generate plot data xpoints = [float(x) for x in range(rangemin,rangemax+1)] ypoints = [] yline = [] for x in xpoints: # ---- fuzzy points for scatter plot d = random.uniform(-2,2) y = x*m + b + d ypoints.append(y) # ---- fixed points for line plot yline.append(x*m + b) # ---- line plot (start and end points) xstartend = [xpoints[0],xpoints[-1]] ystartend = [yline[0],yline[-1]] plt.plot(xstartend,ystartend,'r') # ---- scatter plot plt.scatter(xpoints,ypoints) plt.show()

#!/usr/bin/python3 # ==================================================================== # code example found on the web # ==================================================================== import numpy as np import matplotlib.pyplot as plt x = np.linspace(-3, 3, 30) y = x**2 plt.plot(x, y) plt.show()

#!/usr/bin/python3 # ==================================================================== # code example found on the web # ==================================================================== import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') plt.show()

#!/usr/bin/python3 # ==================================================================== # scatter plot # ==================================================================== import random import matplotlib.pyplot as plt scatter = [-.2,-.1, .2,.3] n = 10 x = np.random.rand(n) y = [] for i in range(len(x)): y.append(x[i] + random.choice(scatter)) plt.scatter(x,y) plt.show()

#!/usr/bin/python3 # ==================================================================== # plot histogram # ==================================================================== import numpy as np import matplotlib.pyplot as plt x = np.random.normal(loc=0, size=200) ##plt.plot(x) plt.hist(x) plt.show()

#!/usr/bin/python3 # ==================================================================== # simple code example I made up # ==================================================================== import matplotlib.pyplot as plt titlestring = 'This is the Plot Title' # list of test data points x = [ 1,2,3,4,5,6,7 ] # x coords y = [ 3,8,3,0,3,2,4 ] # y coords m = 1.5 # line slope b = 0.3 # line y-intercept # ---- plot data points plt.figure(figsize = (10,8)) # plot size plt.plot(x, y, 'b.') # plot x,y as a blue point # ---- plot a line (two points) xx = [x[0],x[-1]] # start and end X coord yy = [m*xx[0] + b, # start Y coord m*xx[1] + b] # end Y coord plt.plot(xx,yy, 'r') # plot (red) line # ---- plot a line (multiple points) # #yy = [ m*v+b for v in x ] # calculate line points based # # on the line equation (y=mx+b) # # one y value for each x value #plt.plot(x,yy, 'r') # plot (red) line # ---- make the plot 'pretty' and show the plot ##plt.figure(figsize=(8,8), layout='tight') plt.figure(layout='tight') plt.xlabel('X Axis', fontsize=14) # X axis label plt.ylabel('Y Axis', fontsize=14) # Y axis label plt.title(titlestring, # plot title string fontweight='bold', # plot title font weight fontsize=18) # plot title font size plt.show()

#!/usr/bin/python3 # ==================================================================== # create a population of random numbers from a theoretical normal # distribution (bell curve) - display various stats and plots # # Base on: realpython.com/numpy-random-normal/ # # To install scipy: python -m pip install scipy # ==================================================================== import scipy.stats import numpy as np import matplotlib.pyplot as plt # ---- create a random number generator rng = np.random.default_rng() # ---- create a list of numbers that fit # ---- a standard normally distributed (bell curve) # ---- default: mean=0 std=1 ary = rng.normal(size=1000) print(f'type ary = {type(ary)}') # data type print(f'len ary = {len(ary)}') # length print(f'mean = {ary.mean()}') # mean print(f'std = {ary.std()}') # standard deviation print(f'max = {ary.max()}') # max value print(f'min = {ary.min()}') # min # ---- bin the data in ary and count the number of values in each bin # ---- i.e. bins are x values and counts are y values counts,bins = np.histogram(ary) print(f'type counts = {type(counts)}') print(f'type bins = {type(bins)}') print(f'len counts = {len(counts)}') print(f'len bins = {len(bins)}') print(f'counts[0] = {counts[0]}') print(f'counts[1] = {counts[1]}') print(f'counts[2] = {counts[2]}') print(f'bins[0] = {bins[0]}') print(f'bins[1] = {bins[1]} bins[0]-bins[1] = {bins[0]-bins[1]}') print(f'bins[2] = {bins[2]} bins[1]-bins[2] = {bins[1]-bins[2]}') # ---- plot a histogram of ary number_of_bins = 100 plt.hist(ary,bins=number_of_bins) # ---- get area of histogram plot bin_width = (ary.max()-ary.min())/number_of_bins hist_area = len(ary)*bin_width # ---- plot a theoretical probability distribution that fits ary x = np.linspace(-4,4,number_of_bins+1) plt.plot(x,scipy.stats.norm.pdf(x)*hist_area) # ---- display plots plt.show()

#!/usr/bin/python3 # ==================================================================== # subplots # ==================================================================== import matplotlib.pyplot as plt if __name__ == "__main__": # ---- plot data x = [1, 2, 3, 4, 5] y = [1, 2, 3, 2, 1] xylen = len(x) # ---- remove mathplotlib toolbar plt.rcParams['toolbar'] = 'None' # ---- two subplots (ax1 and ax2) fig,[ax1,ax2] = plt.subplots(nrows=2, ncols=1, figsize=(10,8), constrained_layout=True) fig.suptitle("Two Subplots", fontsize=16) # ---- subplot #1 ax1.title.set_text("First Subplot") ax1.set_xlabel('X') ax1.set_ylabel('Y') ax1.plot(x,y,'.-') # ---- subplot #2 x1 = x[0:xylen/2] y1 = y[0:xylen/2] ax2.title.set_text("Second Subplot") ax2.set_xlabel('X') ax2.set_ylabel('Y') ax2.plot(x1,y1,'.-') # ---- plot plt.tight_layout() plt.show()

Runtime Configuration Parameters

import matplotlib.pyplot as plt print(f'plt type is {type(plt)}') ## ---- remove toolbar from plot ##plt.rcParams['toolbar'] = 'None' keys = sorted(plt.rcParams.keys()) # ---- display the first 20 key/value pairs for i,k in enumerate(keys[:20]): print(f'[{i:02}] {k:34} {plt.rcParams[k]}')