文章目录
From PythonDataScienceHandbook
4.0
style
plt.style.use('...')
show
在 .py
文件中,plt.show()
应该在脚本的结尾处,且只出现一次,否则会有不可预料的结果。
save figure
fig = plt.figure()
...
fig.savefig('my_figure.png')
show the save figure
from IPython.display import Image
Image('my_figure.png')
object-oriented interface
fig, ax = plt.subplots(2)
这里 fig 和 ax 是数组,可以通过 index 取到对应的 axes (坐标系)
4.1 Simple Line Plot
ax.***
API is similar to plt.***
Color and Style for line plot
plt.plot(x, x + 0, '-g')
plt.plot(x, x + 1, '--k')
plt.plot(x, x + 2, '-.k')
plt.plot(x, x + 3, ':r')
RGB (Red/Green/Blue) and CMYK (Cyan/Magenta/Yellow/blacK)
fmt
link
axis limits
plt.xlim()
plt.ylim()
plt.axis()
limits in axes
axes.set(
)
4.2 Scatter
scatter
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3, cmap='xxx')
这里:
- c 表示颜色深浅
- s 是圈的大小
- alpha 表示不透明度,alpha ->0 越透明
- cmap 是 colorbar 的样式,可以在这里进行选择
show the colorer
plt.colorbar()
Color map in mpl
cyclic colorbar for centered data
4.3 Error
Discrete Error: errorbar
Continuous Error: fill_between
4.4 Contour
contour
, contourf
, imshow
4.5 Histogram
可以用 hist2d
来画 confusion matrix
4.6 Legend
使用 fig, ax = plt.subplot()
的方式。
使用 plot(label='xxx')
对每条线进行标注,'$..$'
可以表示 Latex 公式。
也可以在 legend([list of lines objects], [list of legends])
里写出所有内容。
4.7 Colorbar
plt.imshow(I, cmap='xxx')
plt.colorbar()
用下面的方式可以看到系统能够提供的 colorbar
plt.cm.<TAB>
Ten Simple Rules for Better Figures
一般有三种类型的 cmap
- Sequential colormaps
- Divergent colormaps
- qualitative colormaps
4.8 Subplot
axes
plt.axes()
fig.add_axes()
括号里可以填写 [left, bottom, width, height]
subplot
plt.subplot()
plt.subplots_adjust()
plt.add_subplot()
subplots
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
GridSpec
grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
这一部分最后的那个 Gaussian 真的很常用
4.9 Text
关于 text 的位置,我比较喜欢使用以下方式标注数据
ax.text(..., transform=ax.transData)
这样做的是相对于坐标轴的位置,transAxes
和 transFigure
有其它作用