Matplotlib Cheat Sheet
工作流程¶
- 准备数据
- 建立plot
- plot
- 自定义plot
- 保存plot
- 显示plot
In [ ]:
# 例子
import matplotlib.pyplot as plt
# 1.准备数据
x = [1,2,3,4]
y = [10,20,25,30]
# 2. 建立plot
fig = plt.figure()
ax = fig.add_subplot(111)
# 3. 画图, 4. 自定义
ax.plot(x, y, color='lightblue', linewidth=3)
ax.scatter([2,4,6],
[5,15,25],
color='darkgreen',
marker='^')
ax.set_xlim(1, 6.5)
# 5. 保存
plt.savefig()
# 6. 显示
plt.show()
准备数据¶
1D数据¶
In [ ]:
import numpy as np
x = np.linspace(0, 10, 100)
y = np.cos(x)
z = np.sin(x)
2D Data or Images¶
In [ ]:
data = 2 * np.random.random((10, 10))
data2 = 3 * np.random.random((10, 10))
Y, X = np.mgrid[-3:3:100j, -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'))
建立plot¶
In [ ]:
import matplotlib.pyplot as plt
% matplotlib inline
# % matplotlib notebook # 交互式的, 每次修改都在原图上
Figure¶
In [ ]:
fig = plt.figure()
fig2 = plt.figure(figsize=plt.figaspect(2.0))
Axes¶
所有的绘图都在一个Axes里面. 在大多数情况下, subplot可以满足你的要求. subplot是一个axes中的一个网格系统
In [ ]:
fig.add_axes()
ax1 = fig.add_subplot(221) # row-col-num, 行-列-序数
ax3 = fig.add_subplot(212)
fig3, axes = plt.subplots(nrows=2,ncols=2)
fig4, axes2 = plt.subplots(ncols=3)
Plot常规¶
1D数据¶
In [ ]:
lines = ax.plot(x,y) # 直线
ax.scatter(x,y) # 散点
axes[0,0].bar([1,2,3],[3,4,5])
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') # 上下数据之间填色, 用y1,y2好像更容易理解
向量场¶
In [ ]:
axes[0,1].arrow(0,0,0.5,0.5) # 在座标轴上加箭头
axes[1,1].quiver(y,z) # 2D向量场带箭头
axes[0,1].streamplot(X,Y,U,V) #2D向量场
数据分布¶
In [ ]:
ax1.hist(y) # histogram
ax3.boxplot(y) # Make a box and whisker plot
ax3.violinplot(z) # Make a violin plot
2D 数据或图像¶
In [ ]:
fig, ax = plt.subplots()
im = ax.imshow(img, cmap='gist_earth', # Colormapped or RGB arrays
interpolation='nearest',
vmin=-2,
vmax=2)
In [ ]:
axes2[0].pcolor(data2) # 伪彩色画2D矩阵
axes2[0].pcolormesh(data) # 伪彩色画2D矩阵
CS = plt.contour(Y,X,U) # 等高线
axes2[2].contourf(data1) # 填充等高线
axes2[2]= ax.clabel(CS) # 标记等高线
自定义plot¶
颜色, color bar, color map¶
In [ ]:
plt.plot(x, x, x, x**2, x, x**3)
ax.plot(x, y, alpha = 0.4)
ax.plot(x, y, c='k')
fig.colorbar(im, orientation='horizontal')
im = ax.imshow(img,
cmap='seismic')
点标记¶
In [ ]:
fig, ax = plt.subplots()
ax.scatter(x,y,marker=".") # 用点
ax.plot(x,y,marker="o") # 用大点
线型¶
In [ ]:
plt.plot(x,y,linewidth=4.0)
plt.plot(x,y,ls='solid')
plt.plot(x,y,ls='--')
plt.plot(x,y,'--',x**2,y**2,'-.')
plt.setp(lines,color='r',linewidth=4.0)
文字与标注¶
In [ ]:
ax.text(1,
-2.1, 'Example Graph', style='italic')
ax.annotate("Sine", xy=(8, 0),
xycoords='data', xytext=(10.5, 0),
textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3"),)
数学文字符号¶
In [ ]:
plt.title(r'$sigma_i=15$', fontsize=20)
范围/ 图例/ 其他¶
座标轴范围¶
In [ ]:
ax.margins(x=0.0,y=0.1) # Add padding to a plot
ax.axis('equal') # 纵横比Set the aspect ratio of the plot to 1
ax.set(xlim=[0,10.5],ylim=[-1.5,1.5]) # x-,y-轴的范围
ax.set_xlim(0,10.5) # 另一种轴范围设定方法
图例¶
In [ ]:
ax.set(title='An Example Axes', #设定标题, x-y-轴的标签
ylabel='Y-Axis', xlabel='X-Axis')
ax.legend(loc='best') # 自动选择图例放置最佳位置
座标轴¶
In [ ]:
ax.xaxis.set(ticks=range(1,5), #手动设定x轴标注Manually set x-ticks
ticklabels=[3,100,-12,"foo"])
>>> ax.tick_params(axis='y', # 让y轴标注更长一些. Make y-ticks longer and go in and out
direction='inout', length=10)
Subplot 间距¶
In [ ]:
>>> fig3.subplots_adjust(wspace=0.5, # 调整subplots之间的间距
hspace=0.3,
left=0.125,
right=0.9,
top=0.9,
bottom=0.1)
>>> fig.tight_layout() # 尽量在fig区域把subplots都挤下
外框¶
In [ ]:
ax1.spines['top'].set_visible(False) # 上框不可见
ax1.spines['bottom'].set_position(('outward',10)) # 下框线外移
保存plot¶
保存图像¶
In [ ]:
plt.savefig('foo.png')
保存透明图像¶
In [ ]:
plt.savefig('foo.png', transparent=True)
显示图像¶
In [ ]:
plt.show()
plt.cla() # 清空axis
plt.clf() # 清空整个figure
plt.close() # 关闭窗口