如果在图的右上角添加两个图例,一个在上面,一个在下面

动态 未结 0 167
小小草
小小草 LV1 2023年9月23日 23:40 发表
你可以使用 Matplotlib 库中的 `legend` 函数来添加图例,并通过 `loc` 参数指定图例的位置。下面是一个示例代码,其中 `upper_legend` 和 `lower_legend` 分别表示上方和下方的图例: ```python import matplotlib.pyplot as plt # 绘制图形 fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6], label='Line 1') ax.plot([1, 2, 3], [2, 4, 6], label='Line 2') # 添加图例 upper_legend = ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15), ncol=2) lower_legend = ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2) # 将图例添加到图形中 plt.gca().add_artist(upper_legend) plt.gca().add_artist(lower_legend) plt.show() ``` 在上面的代码中,`bbox_to_anchor` 参数用于指定图例的位置,`(0.5, 1.15)` 表示上方图例的中心点位于图形的正中央偏上一些,`(0.5, -0.15)` 表示下方图例的中心点位于图形的正中央偏下一些。`ncol` 参数用于指定图例的列数,这里设置为 2 表示每行最多显示两个图例项。最后,我们需要使用 `add_artist` 函数将图例添加到图形中,因为默认情况下 `legend` 函数会覆盖掉已有的图例。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复