matplotlib
官方资料:https://matplotlib.org/gallery/index.html
-
创建
- 先创建figure对象(设置figsize)
- 再创建subplot(设置图表布局)
- 绘图
import matplotlib.pyplot as plt
from numpy.random import randn
fig = plt.figure(figsize = (10,5)) #1
ax1 = fig.add_subplot(2,2,1) #2
ax1.plot(randn(50).cumsum(),'k--') #3
※ 由于根据特定布局创建figure和subplot是常见任务,所以可用plt.subplots()创建,返回一个figure对象和一组subplot对象
https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.subplots.html
import matplotlib.pyplot as plt
from numpy.random import randn
#创建一个figure和一个subplot
fig2, axes = plt.subplots()
axes.plot(randn(50).cumsum(),'k--')
#创建一个figure和一行/列subplot
fig3, axes = plt.subplots(1, 2, sharey = True)
axes[0].plot(randn(50).cumsum(),'k--')
axes[1].plot(randn(50).cumsum(),'o--')
#创建一个figure和多个subplot
fig4, axes = plt.subplots(2, 2, sharey = True)
axes[0,1].plot(randn(50).cumsum(),'k--')
axes[1,0].plot(randn(50).cumsum(),'o--')
- 其他
调整subplot周围间距
plt.subplots_adjust(wspace = 0, hspace = 0) #注:轴标签会重叠,需要再调整
调整颜色、标记和线型
https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot
Matplotlib recognizes the following formats to specify a color:
- an RGB or RGBA tuple of float values in
[0, 1]
(e.g.,(0.1, 0.2, 0.5)
or(0.1, 0.2, 0.5, 0.3)
);- a hex RGB or RGBA string (e.g.,
'#0F0F0F'
or'#0F0F0F0F'
);- a string representation of a float value in
[0, 1]
inclusive for gray level (e.g.,'0.5'
);- one of
{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}
;- a X11/CSS4 color name;
- a name from the xkcd color survey; prefixed >with
'xkcd:'
(e.g.,'xkcd:sky blue'
);- one of
{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray','tab:olive', 'tab:cyan'}
which are the Tableau Colors from the 'T10' categorical palette (which is the default color cycle);- a "CN" color spec, i.e.
'C'
followed by a single digit, which is an index into the default property cycle (matplotlib.rcParams['axes.prop_cycle']
); the indexing occurs at artist creation time and defaults to black if the cycle does not include color.
Set the linestyle of the line (also accepts drawstyles, e.g., 'steps--')
linestyle description '-' or 'solid' solid line '--' or 'dashed' dashed line '-.' or 'dashdot' dash-dotted line ':' or 'dotted' dotted line 'None' draw nothing ' ' draw nothing '' draw nothing
Markers
https://matplotlib.org/devdocs/api/markers_api.html#module-matplotlib.markers
调整刻度、标签和图例、注解(略)