Matplotlib¶
【莫烦Python】Matplotlib Python bilibili
plt.tight_layout()
plt.legend(bbox_to_anchor=(1.05, 0), loc='lower left', borderaxespad=0.)
plt.subplots_adjust(hspace=0.5)
支持中文
A12, = plt.plot(xt, c, ls='--', c='black')
plt.legend(handles=[A7, A8, A9, A12], labels=['A7', 'A8', 'A9', 'A12'])
(4条消息) Python: Matplotlib调整子图间距离_RaySunWHUT-CSDN博客_matplotlib 子图间距
Matplotlib: Python plotting — Matplotlib 3.4.2 documentation
matplotlib.pyplot¶
plt.plot()¶
Plot y versus x as lines and/or markers.
import matplotlib.pyplot as plt
plt.plot([x], y, [fmt], *, data=None, **kwargs) # 单线条
plt.plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) # 多线条
eg: plot(y) # plot y using x as index array 0..N-1
# fmt = '[color][marker][line]' 可以用缩写来设置颜色,点型,线型,但用关键字的优先级更高
对多组数据作图
# 法一 plot multiple times
plt.plot(x1, y1, 'bo')
plt.plot(x2, y2, 'go')
# 法二
plt.plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
可选参数:
color
也可以用十六进制的 RGB 字符串,如 color='#900302'
character | color |
---|---|
'b' |
blue 蓝 |
'g' |
green 绿 |
'r' |
red 红 |
'c' |
cyan 蓝绿 |
'm' |
magenta 洋红 |
'y' |
yellow 黄 |
'k' |
black 黑 |
'w' |
white 白 |
marker
只支持简写
character | description |
---|---|
'.' |
point marker |
',' |
pixel marker |
'o' |
circle marker |
'v' |
triangle_down marker |
'^' |
triangle_up marker |
'<' |
triangle_left marker |
'>' |
triangle_right marker |
'1' |
tri_down marker |
'2' |
tri_up marker |
'3' |
tri_left marker |
'4' |
tri_right marker |
's' |
square marker |
'p' |
pentagon marker |
'*' |
star marker |
'h' |
hexagon1 marker |
'H' |
hexagon2 marker |
'+' |
plus marker |
'x' |
x marker |
'D' |
diamond marker |
'd' |
thin_diamond marker |
'|' |
vline marker |
'_' |
hline marker |
linestyle
character | description |
---|---|
'-' |
solid line style 实线 |
'--' |
dashed line style 虚线 |
'-.' |
dash-dot line style 点画线 |
':' |
dotted line style 点线 |
其他
Property | Description |
---|---|
alpha | scalar or None |
markeredgecolor / mec | color |
markeredgewidth / mew | float |
markersize / ms | float |
linewidth / lw | float |
plt.hist()¶
Plot a histogram
matplotlib.pyplot.hist(x, bins=None, density=False, log=False, stacked=False,)
-
x:数据,直方图中会对数据进行统计
-
bins:横坐标区间分布,int or sequence or str,defalut:
None
-
density:False 纵坐标会显示频数,True 纵坐标显示频率,计算方式:density = counts / (sum(counts) * np.diff(bins)),defalut:
False
If stacked is also True
, the sum of the histograms is normalized to 1.
-
log:是否使用指数刻度(科学计数法),defalut:
False
-
stacked: bool,是否为堆积状图,default:
False
堆积柱状图
plt.hist(x = [data1, data2], stacked=True, color = ['g','r'],label = ['Survived','Dead'])
plt.scatter()¶
plt.scatter(x, y, size, color, )
- size:s
- color:c
plt.bar()¶
plt.bar(x, y, facecolor, edgecolor)
plt.boxplot()¶
contour¶
plt.contour()
画等高线
plt.contour([X, Y,], z, colors, lw)
plt.contourf()
contour fill,等高线填充
plt.contourf([X, Y,] Z, [level], **kwargs)
# 如果 XY 都是一维的, 那 z 的行数等于 len(y), 列数等于 len(x)
参数 | 说明 |
---|---|
colors | |
alpha | float, default 1, between 0 (transparent) and 1 (opaque) |
cmap | colormap eg: 热力图 cmap=plt.cm.hot, cmap=plt.cm.cool |
level | 密集程度 eg: plt.contour(X, Y, Z, 8) |
inline | 是否添加等高线的数值 eg: plt.contour(X, Y, Z, inline = True) |
fontsize | 字体大小 eg: plt.contour(X, Y, Z, inline = True, fontsize = 12) |
plt.clabel
给等高线标注
C = plt.contour(x, y, z, 8)
plt.clabel(C, inline=True,fontsize)
plt.imshow()¶
plt.semilogy()¶
matplotlib.pyplot.semilogy — Matplotlib 3.5.0 documentation
误差棒¶
plt.annotate()¶
plt.annotate(str, xy, xycoords, xytext, textcoords, fontsize, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
plt.text()¶
plt.text(x, y, str, fontdict={'size':16, 'color':'r'}, ha, va)
- ha:horizontal alignment,'center','bottom'
- va:vertical alignment
设置坐标轴¶
坐标轴范围¶
plt.xlim()
plt.xlim(*args, **kwargs) # 设置横坐标范围
left, right = xlim() # return the current xlim
plt.xlim((left, right)) # set the xlim to left, right
plt.xlim(right=3) # adjust the right leaving left unchanged
plt.xlim(left=1) # adjust the left leaving right unchanged
plt.yscale()
Set the y-axis scale
plt.yscale(value)
- value:{"linear", "log", "symlog", "logit", ...},比如 log 可以讲 y 轴的值全都取 log10
plt.xlabel()¶
plt.xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs) # 设置xlabel
- xlabel:坐标轴标签,str
- fontdict:字体大小,数字或 'small','large','medium'
- loc: label position,{'left', 'center', 'right'},defalut:
center
plt.xticks()¶
plt.xticks(ticks=None, labels=None)
plt.xticks(rotation=60) # 旋转
- ticks:要显示的坐标
- labels:把 ticks 中的每个数值替换为 labels
plt.xticks(()) # 不显示 x 轴
显示部分坐标¶
会用在横坐标是连续日期且特别多,只需要显示部分即可的情况
import matplotlib.ticker as ticker
plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(20)) # 间隔坐标数
gca:'get current axis'
移动坐标轴¶
ax = plt.gca()
ax.spines['right'].set_color('none') # 让上面的脊消失
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom') # 用下面的脊代替xaxis
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0)) # 移动坐标轴
ax.spines['left'].set_position(('data', 0))
绘制多图¶
plt.figure()¶
Create a new figure, or activate an existing figure
plt.figure(num=None, figsize=None, dpi=80, facecolor=None, edgecolor=None, frameon=True)
- num:图像编号或名称,int or str
- figsize:figure 的宽和高,default:
[6.4, 4.8]
- dpi:resolution,指定分辨率,default:
100.0
- facecolor:background color,default:
'white'
- edgecolor:border color,default:
'white'
- frameon:显示边框与否,default:
True
# eg
plt.figure(num=1, figsize(4, 3))
plt.plot(...)
plt.figure(num=2, figsize(4, 3))
plt.plot(...)
plt.show() # 会显示 2 张图
plt.subplot()¶
绘制子图,在同一张图上绘制多张图
plt.subplot(nrows, ncols, index, **kwargs) # default: (1, 1, 1)
- nrows:行数
- ncols:列数
- index:编号
# eg
plt.subplot(221) # nrows=2, ncols=2, index=1 的简写
plt.plot(...)
...
plt.subplots()¶
plt.subplots(nrows=1, ncols=1)
Create a figure and a set of subplots
Return: - fig: Figure - ax: axes.Axes or array of Axes
fig, ax = plt.subplots(2, 2)
ax[0][0].plot(...) # 绘制第一张图
...
图例¶
plt.legend(handles=[], labels=[], loc='best')
- loc:legend 位置,'best','upper right' ....
plt.plot(x, y, label='test')
plt.legend()
l1, = plt.plot(x1, y1)
l2, = plt.plot(x2, y2)
plt.legend(handles=[l1, l2], labels=['1', '2'], loc='best')
plt.legend(handles=[l1, ], labels=['1', ], loc='best')
其他¶
plt.colorbar()
plt.colorbar()
cmap¶
设置颜色
# 以灰度图为例
cmap = plt.get_cmap('Greys') # 等效于 cmap = plt.cm.Greys
norm = plt.Normalize(vmin=-3, vmax=3) # 将数值范围标准化,投影到所选的颜色集上
plt.imshow(grid.T , extent=(0, 1, 0, 1), cmap=cmap, norm=norm) # 绘图
Axes¶
Axes.set_title()¶
matplotlib.axes.Axes.set_title
Axes.xaxis¶
子图的横坐标轴设置
纵坐标轴:Axes.yaxis
Axes.xaxis.set_visible(False) #隐藏坐标轴
其他¶
matplotlib.use(‘agg’)# 在执行import matplotlib.pyplot as plt前运行, 不会显示绘图
%matplotlib inline¶
可以在 jupyter notebook 中内嵌显示图片
fig.axes.annotate¶
7.1 优化与深度学习 - Dive-into-DL-PyTorch (tangshusen.me)
保存图片¶
plt.savefig(path)
重叠问题¶
输出的图片内容有重叠,如有多个子图时
# 可能的解决办法
plt.tight_layout() # 在要显示或者保存之前
注意事项¶
- plt.savefig 必须要在 plt.show 前面,因为 plt.show 会释放资源
参考¶
matplotlib.pyplot.plot()参数详解_ims的博客-CSDN博客
matplotlib.pyplot contourf()函数的使用_lens_的博客-CSDN博客