1 Plot Workflow

  1. prepare data
  2. Crete plot
  3. plot
  4. customize plot
  5. save plot
  6. show plot
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [11,23,44,66] # step 1

fig = plt.figure() # step 2 

ax = fig.add_subplot(111) # step3

# fig,ax = plt.subplots()

ax.plot(x,y,color = "red") # step 3,4

ax.scatter([2,4,6],[6,11,17],color="blue",marker='^')

ax.set_xlim(1,7)

# plt.savefig("p.png")
## (1, 7)
plt.show()

2. prepare data

import numpy as np

x = np.linspace(0,10,100)
y = np.cos(x)
z = np.sin(x) # 1 D 


data = 2 * np.random.random((10,10))
data2 = 3 * np.random.random((10,10))

Y,X = np.mgrid[-3:3:100,-3:3:100j]
U = -1 - X**2 +Y
V = 1 + X - Y**2

from matplotlib.cbook import get_sample_data
img =  np.load(get_sample_data('axes_grid/bivariate_normal.npy'))

3 create plot

import matplotlib.pyplot as plt

fig = plt.figure()
fig1 = plt.figure()

Axes

All plotting is done with respect to an Axes. In most cases, a subplot will fit your needs. A subplot is an axes on a grid system

fig.add_axes()

ax1 = fig.add_subplot(111) # row col num
ax2 = fig.add_subplot(222)

fig3,axes = plt.subplots(nrows=2,ncols=2)
fig4,axes1 = plt.subplots(ncols=3)

4 ploting

1D data

line = ax.plot(x,y)
# plt.show()
ax.scatter(x,y)

axes[0,0].bar([1,2,3],[4,5,6])
axes[1,0].barh([0.5,1,2.5],[0,1,2])
axes[1,1].axhline(0.45)
axes[0,1].axvline(0.65)
ax.fill(x,y,color='blue')
ax.fill_between(x,y,color='yellow')

3D

fig, ax = plt.subplots()
 
im = ax.imshow(img,cmap='gist_earth', interpolation='nearest',vmin=-2,vmax=2)

Vector Fields

axes[0,1].arrow(0,0,0.5,0.5)
axes[1,1].quiver(y,z)

axes[0,1].streamplot(X,Y,U,V)

Data Distributions

 ax1.hist(y)
 ax3.boxplot(y)
 ax3.violinplot(z)

4 customize plot

plt.plot(x, x, x, x**2, x, x**3)
ax.plot(x, y, alpha = 0.4)
ax.plot(x, y, c='k')

其他参数还包括:

  1. marker
  2. linewidth/ ls=‘–’

add text

ax.text(1,2,"text")

5 save plot

plt.savefig("p.png")

6 show plot

plt.show()

7 close / clear

plt.cla() # clear an axis 
plt.clf() # clear the entire figure
plt.close()

8 more …