Matplotlib子图外侧添加文本失败问题求助
给每组子图左侧添加文本的解决方法
我想在每组子图的左侧添加描述文本(比如“Distance ≤6.5 km”),但尝试用plt.annotate()或plt.text()时,文本总是只显示在最后一个子图里,原代码如下:
import numpy as np import numpy.random as rd import matplotlib.pyplot as plt Dic_Values = {'inf_6.5':{'v_moy':rd.randint(15,25, 20), 'cad':rd.randint(75,100,20), 'f_moy':rd.randint(130,180,20)}, '6.5_9.5':{'v_moy':rd.randint(15,25, 11), 'cad':rd.randint(75,100,11), 'f_moy':rd.randint(130,180,11)}, 'sup_9.5':{'v_moy':rd.randint(15,25, 4), 'cad':rd.randint(75,100,4), 'f_moy':rd.randint(130,180,4)}} def bilan_course(): types = list(Dic_Values.keys()) c = 0 plt.figure(figsize=(21,7)) Labels = ['S_moy', 'Cad', 'F_moy'] Y_axis = ['S (in $km \cdot h^{-1}$)', 'Cad (in $step\cdot min^{-1}$)', 'F (in $beat\cdot min^{-1}$)'] for ty in types: Donnees = Dic_Values[ty] Cles = list(Donnees.keys()) for v in range(len(Cles)): plt.subplot(int('33'+str(3*c+v+1))) plt.plot(Donnees[Cles[v]], label=Labels[v]) plt.xlabel('Course') plt.ylabel(Y_axis[v]) plt.title(Labels[v]) plt.ylim(0, max(Donnees[Cles[v]])*1.1) plt.legend(loc='best') c+=1 plt.subplots_adjust(left=0.1, bottom=0.085, right=0.95, top=0.882, wspace=0.25, hspace=0.5) plt.annotate('Distance $\leq6.5$ $km$', (1, 1), fontsize=12) plt.suptitle('Summary', fontweight='bold') plt.show()
问题原因
plt.annotate()和plt.text()默认会将文本添加到当前活跃的子图上。你的代码在所有子图绘制完成后才调用这两个方法,此时活跃子图是最后一个,所以文本只会出现在那里。
解决方法
使用画布(figure)的全局坐标系统添加文本,能精准控制文本位置,不受当前子图影响。具体修改如下:
import numpy as np import numpy.random as rd import matplotlib.pyplot as plt Dic_Values = {'inf_6.5':{'v_moy':rd.randint(15,25, 20), 'cad':rd.randint(75,100,20), 'f_moy':rd.randint(130,180,20)}, '6.5_9.5':{'v_moy':rd.randint(15,25, 11), 'cad':rd.randint(75,100,11), 'f_moy':rd.randint(130,180,11)}, 'sup_9.5':{'v_moy':rd.randint(15,25, 4), 'cad':rd.randint(75,100,4), 'f_moy':rd.randint(130,180,4)}} def bilan_course(): types = list(Dic_Values.keys()) # 定义每组子图对应的左侧描述文本 group_labels = ['Distance $\leq6.5$ $km$', '6.5 $km$ < Distance $\leq9.5$ $km$', 'Distance $>9.5$ $km$'] c = 0 fig = plt.figure(figsize=(21,7)) Labels = ['S_moy', 'Cad', 'F_moy'] Y_axis = ['S (in $km \cdot h^{-1}$)', 'Cad (in $step\cdot min^{-1}$)', 'F (in $beat\cdot min^{-1}$)'] for ty in types: Donnees = Dic_Values[ty] Cles = list(Donnees.keys()) for v in range(len(Cles)): # 获取当前子图的axes对象,改用面向对象写法更清晰 ax = plt.subplot(int('33'+str(3*c+v+1))) ax.plot(Donnees[Cles[v]], label=Labels[v]) ax.set_xlabel('Course') ax.set_ylabel(Y_axis[v]) ax.set_title(Labels[v]) ax.set_ylim(0, max(Donnees[Cles[v]])*1.1) ax.legend(loc='best') # 在每组子图左侧添加文本,使用figure的全局坐标(范围0-1,左下角为(0,0)) # x=0.02 贴近左侧边缘,y坐标根据组的位置调整为垂直中心 fig.text(0.02, 0.8 - c*0.3, group_labels[c], fontsize=12, va='center') c += 1 plt.subplots_adjust(left=0.1, bottom=0.085, right=0.95, top=0.882, wspace=0.25, hspace=0.5) plt.suptitle('Summary', fontweight='bold') plt.show() # 调用函数生成图像 bilan_course()
修改说明
- 新增
group_labels列表,对应每组子图的描述文本; - 改用
fig.text()添加文本,通过全局坐标系统指定位置,避免受活跃子图影响; - 将原有的
plt.xxx方法替换为ax.xxx(面向对象写法),代码逻辑更清晰; - 调整
subplots_adjust的left参数预留足够空间显示左侧文本。
内容的提问来源于stack exchange,提问作者AliStonks
相关产品推荐
相关产品推荐

