- matplotlib: **kwargs: `.Text` properties can be used to control the appearance of the labels.
- matplotlib: The PDF backend does not currently support the selected font.
- matplotlib打印微秒
- matplotlib生成没有留白的图片
- matplotlib箱线图调整箱子的宽度
- matplotlib中使用latex
¶ pyplot
import matplotlib.pyplot as plt
yscale: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.yscale.html
非阻塞显示图片:plt.show(block=False)
开始画下一张:plt.figure()
¶ 散点图 plt.scatter
交互式散点图:https://mpld3.github.io/examples/scatter_tooltip.html
¶ legend
要用Line2D
画: https://stackoverflow.com/questions/47391702/how-to-make-a-colored-markers-legend-from-scratch
调整宽度用legend
的参数handlelength
:
https://stackoverflow.com/questions/66809947/matplotlib-change-length-of-legend-lines
https://stackoverflow.com/questions/20048352/how-to-adjust-the-size-of-matplotlib-legend-box
¶ 折线图 plt.plot
plt.plot(y)
的横坐标是从0开始的数组下标。
¶ plt.legend
- matplotlib设置legend坐标
frameon
: bool, default: rcParams["legend.frameon"] (default: True)
Whether the legend should be drawn on a patch (frame).
handletextpad
: float, default:0.8
The pad between the legend handle and text, in font-size units.
columnspacing
: float, default:2.0
The spacing between columns, in font-size units.
¶ 'plt.ylabel'
loc
: {'bottom', 'center', 'top'}, default:center
其他参数传给了Text。常用的:
y
可以微调高度
¶ text
Positional, required:
x, y
: floats
: str
Optional:
fontsize
transform
The default transform specifies that text is in data coords.
transform=ax.transAxes
: in axis coords. (0, 0) is
lower-left and (1, 1) is upper-right.
¶ tight_layout
pad
: float, default: 1.08.h_pad, w_padfloat
: default: pad
Padding (height/width) between edges of adjacent subplots, as a fraction of the font size.
¶ Axes
= plt.gca() ax
文档:https://matplotlib.org/stable/api/axes_api.html
来源:https://stackoverflow.com/questions/15067668/how-to-get-a-matplotlib-axes-instance
¶ tick_params
ax.tick_params(axis='y', which='major', labelsize=8)
¶ set_title
Positional, required: label
Optional: fontdict
¶ set_xticks
Positional, required: ticks
Optional: labels
(list-like)
¶ set_xlabel
跟plt.xlabel
一样。
Positional, required: xlabel
Optional: labelpad
, fontsize
loc
: {'left', 'center', 'right'}, default: rcParams["xaxis.labellocation"] (default: 'center')
比方说如果xlabel超过了右边界,可以设置loc='right'
来让它与右边界对齐,就不会超过右边界了。
¶ set_xlim, set_ylim
设置Y轴最小值:
=0) ax.set_ylim(bottom
来源:https://stackoverflow.com/a/22642641/13688160
¶ set_yscale
'log') ax.set_yscale(
¶ annotate 画箭头
text
xy
: (float, float)
The point (x, y) to annotate. The coordinate system is determined by xycoords.
xytext
: (float, float), default: xy
The position (x, y) to place the text at. The coordinate system is determined by textcoords.
xycoords
,textcoords
: default: 'data'
完整列表见文档。这里放常用的。
Value | Description |
---|---|
data |
Use the coordinate system of the object being annotated (default) |
figure fraction |
Fraction of figure from lower left |
subfigure fraction |
Fraction of subfigure from lower left |
axes fraction |
Fraction of axes from lower left |
其他参数传给了Text。常用的:
fontsize
weight
常用值:bold
参考:https://stackoverflow.com/questions/36162414/how-to-add-bold-annotated-text-to-a-plot
¶ ticklabel_format
比如把tick设置成
='sci', scilimits=(4, 4), useMathText=True) ax.ticklabel_format(style
¶ tick formatter
文档:https://matplotlib.org/stable/gallery/ticks/tick-formatters.html
例子:
lambda x, pos: str(x-5)) ax1.xaxis.set_major_formatter(
¶ 指定指数
比如指定指数为1e-9:
from matplotlib.ticker import ScalarFormatter
= ScalarFormatter()
y_formatter -9, -9))
y_formatter.set_powerlimits(( ax.yaxis.set_major_formatter(y_formatter)
官方文档:https://matplotlib.org/stable/api/ticker_api.html#matplotlib.ticker.ScalarFormatter.set_powerlimits
来源:https://stackoverflow.com/a/77442842/13688160
设置fontsize:
8) ax.yaxis.get_offset_text().set_fontsize(
来源:https://stackoverflow.com/a/34228384/13688160
¶ set_label_coords
例子:
0.1, -0.19) ax.xaxis.set_label_coords(
¶ grid
官方文档:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.grid.html
让参考线在柱状图的柱子后面:
# https://stackoverflow.com/a/68344604
True) ax.set_axisbelow(
给y轴画参考线:
='y') ax.grid(axis
¶ colorbar
https://matplotlib.org/stable/users/explain/colors/colormapnorms.html
例子:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors
= plt.gca()
ax = plt.get_cmap('coolwarm')
cmap
# need to normalize because color maps are defined in [0, 1]
= colors.TwoSlopeNorm(1, vmin=0, vmax=5)
norm
= cm.ScalarMappable(norm=norm, cmap=cmap)
norm_cmap
for i in np.linspace(0, 5, 100):
=norm_cmap.to_rgba(i))
plt.scatter(i, i, color= plt.colorbar(norm_cmap, ax=ax, ticks=[0, 0.5, 1, 2, 3, 4, 5])
cb =8)
cb.ax.tick_params(labelsize plt.show()
参考:
https://stackoverflow.com/questions/73510185/how-to-add-colorbar-in-matplotlib
¶ 翻转坐标轴
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.invert_yaxis.html
¶ 子图
¶ gridspec
官方文档:https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html
常用:
= plt.figure(dpi = 300, figsize = (xx, xx), constrained_layout=True)
figure = gridspec.GridSpec(1, 3, figure=figure) gs
其中constrained_layout
比tight_layout
更好。
plt.figure
参数:https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure
¶
plt.subplot
共用坐标轴:Shared axis
¶ 调整坐标轴label与tick label之间的空隙
用labelpad
官方文档:https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.xlabel.html
¶ 设置tick的个数
比如让y轴有4个tick:
='y', nbins=4) plt.locator_params(axis
来源:https://stackoverflow.com/a/13418954/13688160
很坑的是,log scale用这种方式无效,需要手动设置ticks:
'log')
plt.yscale(# 设置成log scale似乎会清空ticks,所以要把设置ticks放后面
1e5, 1e6, 1e7], fontsize=8)
plt.yticks([# plt.yticks似乎会消除minor ticks,所以还得把它们补上
# 其中numticks比较玄学,似乎大于3就行。这里直接设置成一个大数,就肯定不会有问题了。
=10, subs=np.arange(2, 10) * 0.1, numticks=233)) ax.yaxis.set_minor_locator(LogLocator(base
¶ 疑难杂症
¶
Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
sudo apt install python3-tk
¶
在安装了ttf-mscorefonts-installer
的情况下matplotlib
找不到Times
New Roman
sudo apt install msttcorefonts -qq
rm ~/.cache/matplotlib -rf
参考:https://stackoverflow.com/questions/42097053/matplotlib-cannot-find-basic-fonts
¶ 已知的问题
plt.legend
顺序似乎只能是按列的,要改成按行只能手动reorder:
https://stackoverflow.com/questions/29639973/custom-legend-in-pandas-bar-plot-matplotlib