如何为matplotlib多子图添加统一全局图例并调整摆放位置
我尝试使用另一组数据复现下图效果:
目前我绘制的图表除右上角图例外其余元素均已完成,但不知道如何基于现有代码添加该图例,现有代码如下:
fig = plt.figure() plt.subplot(3, 1, 1) plt.title('Task Switches and Avg Task Switches by Timestep', fontsize=10) plt.ylabel('Task Switches', fontsize=9) plt.xlim(-35, timestep_num + 35) plt.xticks(np.arange(0, timestep_num+1, 50), fontsize=-1, color='white') plt.yticks(np.arange(0, 61, 20), fontsize=6) plt.plot([stepsum_list[i][6] for i in range(len(stepsum_list))], color='royalblue', linewidth=0.7, linestyle='', marker='.', markersize=1) plt.plot([stepsum_list[i][6]/(i+1) for i in range(len(stepsum_list))], color='limegreen', linewidth=0.6,) plt.subplot(3, 1, 2) plt.title('Task Demand per Timestep by Task', fontsize=10) plt.ylabel('Task Demand', fontsize=9) plt.xlim(-35, timestep_num + 35) plt.xticks(np.arange(0, timestep_num+1, 50), fontsize=-1, color='white') plt.yticks(np.arange(0, 6, 1), fontsize=6) plt.plot([stepdem_list[i][1] for i in range(len(stepdem_list))], color='darkorange', linewidth=0.7, linestyle='', marker='.', markersize=1) plt.plot([stepdem_list[i][2] for i in range(len(stepdem_list))], color='yellowgreen', linewidth=0.7, linestyle='', marker='.', markersize=1) plt.plot([stepdem_list[i][3] for i in range(len(stepdem_list))], color='purple', linewidth=0.7, linestyle='', marker='.', markersize=1) plt.plot([stepdem_list[i][4] for i in range(len(stepdem_list))], color='blue', linewidth=0.7, linestyle='', marker='.', markersize=1) plt.subplot(3, 1, 3) plt.title('Target and Tracker Movement',fontsize=10) plt.ylabel('Movement', fontsize=9) plt.xlabel('Timesteps', fontsize=9) plt.xlim(-35, timestep_num + 35) plt.xticks(np.arange(0, timestep_num+1, 50), fontsize=8) plt.yticks(np.arange(-10, 11, 10), fontsize=6) plt.plot([stepsum_list[i][4] for i in range(len(stepsum_list))], color='blue', linewidth=.5) plt.plot([stepsum_list[i][2] for i in range(len(stepsum_list))], color='red', linewidth=.5) fig.align_labels() plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.4, hspace=0.4) plt.savefig('prog02_output.png') plt.show
抱歉代码存在较多重复,我是Python新手,这是我第一次绘图,还不了解相关优化技巧。我已经找到了figlegend()函数,但不确定是否是我需要的工具,也不清楚其参数使用规则。另外我还希望将图例放置在和顶部子图对齐的正确位置,但一直没有找到实现方法。
我不需要大家直接编写或重写我的代码,仅希望得到正确的方向指引:比如可以解释相关函数的作用和可用参数,或者说明我现有代码需要做哪些调整即可使用figlegend()实现需求。
实现指引
- 先给所有绘图语句加标签
你现在调用plt.plot()的时候没有指定label参数,这是生成图例的基础。给每个你需要放进图例的线条都加上label='对应名称'参数,名称就是你要在图例里显示的文本。 - 调整画布边距预留图例位置
在plt.subplots_adjust()里修改right参数,比如设为0.8,给画布右侧留出足够的空白放置图例,避免图例被截断。 fig.legend()核心参数说明
你找的fig.legend()就是用来生成整幅画布级图例的工具,刚好符合你的需求,核心常用参数如下:
- 不需要额外传
handles和labels的情况下,函数会自动收集所有带label参数的绘图对象生成图例,逻辑最简单 loc:控制图例的锚点位置,填字符串即可,比如要放在右上角就用'upper right'bbox_to_anchor:用来精准指定图例的位置,你要和顶部子图对齐的话,可以先把顶部子图赋值给一个变量比如ax1 = plt.subplot(3,1,1),然后用bbox_to_anchor=ax1.get_position()获取顶部子图的位置范围,再微调数值就能对齐到你要的位置
- 调用时机
把fig.legend()放在所有绘图语句结束之后、plt.savefig()之前调用即可。
内容的提问来源于stack exchange,提问作者WeekendJedi
相关产品推荐
相关产品推荐

