matplotlib画图

基本设置

设置中文

1
2
plt.rcParams['font.sans-serif']=['SimHei']   # 设置中文字体,使其能够显示中文
plt.rcParams['axes.unicode_minus']=False # 解决上述设置后不能正常显示正负号的问题

主题设置

1
2
plt.style.available         # 查看可用主题
plt.style.use("seaborn") # 修改主题

主题列表:

‘Solarize_Light2’, ‘_classic_test_patch’, ‘bmh’, ‘classic’, ‘dark_background’, ‘fast’, ‘fivethirtyeight’, ‘ggplot’, ‘grayscale’, ‘seaborn’,‘seaborn-bright’, ‘seaborn-colorblind’,‘seaborn-dark’, ‘seaborn-dark-palette’, ‘seaborn-darkgrid’, ‘seaborn-deep’, ‘seaborn-muted’, ‘seaborn-notebook’, ‘seaborn-paper’, ‘seaborn-pastel’, ‘seaborn-poster’, ‘seaborn-talk’, ‘seaborn-ticks’, ‘seaborn-white’, ‘seaborn-whitegrid’, ‘tableau-colorblind10’

边框设置

1
2
3
4
plt.axis('off')    # 去掉所有边框

ax.spines['right'].set_visible(False) # 设置某一条框线可见性
ax.spines['bottom'].set_linewidth(5) # 设置某一条框线的线宽

画布设置

1
2
3
plt.rcParams['figure.dpi'] = 150     # 设置全局分辨率
plt.figure(figsize=(15,10), dpi=150) # 设置画布大小,局部分辨率
fig.set_size_inches(5,4) # 设置画布大小

获取ax对象

1
2
3
# 获取ax对象
fig, ax = plt.subplots()
ax = plt.gca()

画图

折线图

1
2
3
4
5
6
7
plt.plot(x, y, 'r-v', linewidth=1.2, markersize=5)
# linewidth线宽,markersize标注尺寸
ax.plot(x, y, 'r-v')
# 样式包括三部分:
# 颜色r,g,b,grey,black,purple
# 线形-,--,=
# 标注v,^,*,.,x

bar图

1
2
3
4
5
6
7
# hatch: / , \ , | , - , + , x , o , O , . , * 。字符重复量表示标注密度
ax.bar(x, y,width=0.5,align="center",label='',color = colors, edgecolor = '', linestyle='-.', lw=2, hatch='/')
plt.bar(x, y,width=0.5,align="center",label='',color = colors, edgecolor = '', linestyle='-.', lw=2, hatch='/')

# 设置hatch标注的格式
plt.rcParams['hatch.color']="grey"
plt.rcParams['hatch.linewidth']=0.5

heat map热图(图片)

1
plt.imshow(matrix, aspect='auto')    # 画heatmap并将长度宽度自适应缩放为合适大小

等高线图、等高线轮廓图

1
2
plt.contour()        # 等高线轮廓图
plt.contourf() # 等高线图

画布元素

标题

1
plt.title('')    # 设置图表标题

文本标注

1
2
for a,b in zip(x, y):
plt.text(a-0.05, b, '%.3f' % b, ha='center', va= 'bottom',fontsize=13,color='black') # a横坐标,b纵坐标,%.3f标注格式

横纵坐标

1
2
3
4
5
6
7
8
9
10
11
# 设置横纵坐标轴标题
ax1.set_xlabel('$\mu$',fontsize=15) # 可设置LaTeX公式
ax1.set_ylabel('',fontsize=15)

# 设置横纵坐标刻度
plt.xticks(x, Mu, fontsize=15, rotation=-45) # 字体大小,旋转(逆时针)
plt.yticks(fontsize=15)

# 设置横纵坐标范围
plt.xlim([])
plt.ylim([5.75,7.2])

图例

1
2
plt.plot(x, y, label="")    # label中设置图例名称
plt.legend(loc='lower right') # 设置图例

网格

1
plt.grid(True,which='major',linestyle='--',linewidth=5)    # 为图片设置网格

颜色

设置背景颜色

1
ax.set_facecolor('#e3e3e3')

给定颜色

1
2
3
4
5
import matplotlib as mpl
colors = ['white', '#FFF8E1', '#FFD54F', '#F57F17','#E65100']
cmap = mpl.colors.ListedColormap(colors) # 将颜色转换为colormap

plt.imshow(np.random.randn(30,30),cmap=cmap)

自动改变颜色

1
2
3
4
5
import matplotlib.colors as mcolors

colors=list(mcolors.TABLEAU_COLORS.keys()) # 获取颜色列表
for i in range():
color=mcolors.TABLEAU_COLORS[colors[i]] # 取index为i对应的颜色

获取渐变颜色

1
2
3
4
# 渐变颜色归一化
map_vir = cm.get_cmap(name='viridis') # viridis, plasma, inferno, magma, cividis
norm = plt.Normalize(5.5,7) # 数值归一化的平均值和标准差
colors = map_vir(norm(MSE_loss)) # 映射到颜色

渐变标注条

1
2
3
4
# 设置渐变标注条
sm = cm.ScalarMappable(cmap=map_vir,norm=norm)
sm.set_array([])
plt.colorbar(sm)

子图

划分子图

1
2
plt.subplot(num_x_subplot, num_y_subplot, i)    # 子图总行数、列数,当前子图的位置
plt.subplots_adjust(wspace=0, hspace=0) # 子图之间的左右间距,上下间距倍数

子图图例合并放置于大图中

1
2
3
4
5
6
7
8
9
10
11
12
# 将label统一放到大图中
lines = []
labels = []

for ax in fig.axes:
axLine, axLabel = ax.get_legend_handles_labels() # 获取子图的线型和label
lines.extend(axLine[:-1])
labels.extend(axLabel[:-1])
lines.extend(axLine[-1:])
labels.extend(axLabel[-1:])

plt.legend(lines, labels, loc='lower right') # 设置大图的图例

图片保存

1
plt.savefig('图片名称.svg',dpi=600,bbox_inches='tight') # 保存时选择窄边框

ubuntu下字体安装问题

matplotlib没有检测到ubuntu下的字体,首先查看matplotlib的缓存目录:

1
2
import matplotlib.font_manager
matplotlib.font_manager.get_cachedir() # 查看matplotlib的缓存目录
1
2
apt install font-manager   # 安装字体管理器
rm -r ~/.cache/matplotlib # 删除matplotlib缓存,以便后续重建

最后重启程序。