Skip to content

Instantly share code, notes, and snippets.

@nafeesb
Last active September 28, 2022 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nafeesb/42d48694858cbbec532670654a74f017 to your computer and use it in GitHub Desktop.
Save nafeesb/42d48694858cbbec532670654a74f017 to your computer and use it in GitHub Desktop.
Matplotlib recipes

Images and Matrices

Load image with imageio

import imageio
import matplotlib.pyplot as plt
img = imageio.imread('file.jpg')
plt.imshow(img)

Load image with PIL

from PIL import Image
buf = Image.open('file.jpg')
img = np.array(buf)

Display image file

from IPython.display import Image
Image('file.png')

Visualize matrices

plt.matshow( mat, aspect='auto' )
plt.colorbar()
plt.show()

Visualize sparsity

plt.spy( mat, precision=1e-5, markersize=2)

Renormalize and save float image as 8-bit pixels

import imageio
import numpy as np

img = np.random.rand( 100,  100, 3 ) # ( width, height, rgb ) yea, it's weird.  just for illustration purposes
img /= np.amax(img, (0,1))
pixels = np.astype( np.uint8 )
imageio.imsave( 'file.jpg', pixels )

Global Settings

Change inline display dpi

import matplotlib as mpl
mpl.rcParams['figure.dpi']=100

Plot Settings

Set figure size

plt.figure(figsize=(8,6), dpi=100)  # 8-inch by 6-inch -> 800x600

Change axis fontsize

plt.tick_params(labelsize=4)

Set border color

fig = plt.figure(figsize=[8, 8], facecolor='white')

Plot Colors

# importing libraries
import matplotlib.pyplot as plt
import numpy as np
  
# giving values for x and y to plot
x = np.arange(0, 10, .1)
y = np.sin(x)
  
# Set background color of the outer 
# area of the plt
plt.figure(facecolor='yellow')
  
# Plotting the graph between x and y
plt.plot(x, y)
  
# Giving x label using xlabel() method
# with bold setting
plt.xlabel("X")
ax = plt.axes()
  
# Setting the background color of the plot 
# using set_facecolor() method
ax.set_facecolor("violet")
  
# Giving y label using xlabel() method with
# bold setting
plt.ylabel('sin(x)')
  
# Showing the plot using plt.show()
plt.show()

Plots with labels

plt.plot( test_comps, np.amax(mse, axis=1) )
plt.ylabel( 'Max MSE' )
plt.xlabel( 'No. of components' )

Interactive 3d plots

# set Tools->Preferences->IPython console->Graphics->Backend to Automatic. Restart.
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x,y,z)

Data series legend

plt.plot(totals[50:,1], label='Body RBFs') # total mlrbf
plt.plot(totals[50:,2], label='Non-body RBFs') # nonbody rbf
plt.plot(totals[50:,0], label='Total Bodylogic') # total bodylogic
plt.ylabel('Time (ms)')
plt.xlabel('Frame')
plt.legend()
plt.show()

Multiple Plots and Multichannel Arrays

Multiple datasets on same plot, equal axis

plt.axis('equal')
plt.scatter( markers[:,0,0], markers[:,0,1], marker='+' )
plt.scatter( markers[:,1,0], markers[:,1,1], marker='o')
plt.show()

Legends for plot multichannel arrays

y = np.random.rand(10,3)
line = plt.plot(y)
plt.legend(line, ('x','y','z'))

lines = plt.plot(y)
plt.legend(lines, ['Line: %d' % v for v in range(len(lines))])

fig = plt.figure(1, figsize=(6,2), dpi=100)
ax = plt.subplot(111)
lines = ax.plot( y )
fig.legend(iter(lines), ('x','y','z'))

Moving average

N = 100
means = np.convolve(x, np.ones((N,))/N, mode='valid')
means = np.append(np.zeros(N-1), means) # pad beginning with zero

plt.figure(2)
plt.plot(x)
plt.plot(means)
plt.show()

Filter 1-D

from scipy.signal import savgol_filter
def filter_foot_vel(y):
    yhat = savgol_filter( y, 31, 1, axis=0)
    return yhat

Histograms

Normal use

Histogram with 50 bins.

plt.hist(A,50,density=True)

Histograms with set bins

from matplotlib.ticker import FormatStrFormatter

bins = np.array([ np.std(ypos) * 0.25 * s for s in range(1,6) ])
bins = np.vstack((bins[::-1]*-1,bins)).ravel() + np.mean(ypos)

fig,ax = plt.subplots()
ax.hist(ypos,bins=bins,edgecolor='k',alpha=0.5)
ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
plt.xticks(bins)
plt.show()

Polar plots with title pad and fontsize

sac_theta = interp(np.random.rand(N) * 100)
sac_r = np.arctan(np.deg2rad(A))

plt.figure(figsize=(3, 3), dpi=140)
ax = plt.subplot(111, projection='polar')
ax.scatter(sac_theta, sac_r, s=6, alpha=0.5)
ax.tick_params(axis='both', labelsize="8")
ax.set_rmax(1)
ax.set_yticklabels([])
ax.set_title('Saccade Distribution', pad=20, fontsize="9")
plt.show()

Subplots

plt.figure(figsize=(8,6), dpi=100)

ax1 = plt.subplot(131)
plt.axis('off')
plt.imshow(img)

ax2 = plt.subplot(132)
plt.axis('off')
plt.imshow(pred)

ax3 = plt.subplot(133)
plt.axis('off')
idiff = np.abs(pred-img)
plt.imshow(idiff*10)

Two subplots with different size

fig,(ax,axb) = plt.subplots(2,1,figsize=(12,12),gridspec_kw={'height_ratios': [2, 1]})

Space between subplots

plt.subplots_adjust(hspace=0.3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment