首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Matplotlib with "secondary_y":如何将图例重新定位到左下角?

在Matplotlib中,可以使用"secondary_y"参数来创建具有两个y轴的图表。要将图例重新定位到左下角,可以使用legend()函数的loc参数来指定图例的位置。

以下是将图例重新定位到左下角的步骤:

  1. 导入必要的库和模块:
代码语言:txt
复制
import matplotlib.pyplot as plt
  1. 创建一个图表对象和两个子图对象:
代码语言:txt
复制
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
  1. 绘制数据到两个子图对象上:
代码语言:txt
复制
ax1.plot(x, y1, 'r-', label='y1')
ax2.plot(x, y2, 'b-', label='y2')
  1. 合并两个子图的图例:
代码语言:txt
复制
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='lower left')

完整的代码示例:

代码语言:txt
复制
import matplotlib.pyplot as plt

# 数据
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 30, 40, 50]
y2 = [5, 10, 15, 20, 25]

# 创建图表和子图
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# 绘制数据到子图上
ax1.plot(x, y1, 'r-', label='y1')
ax2.plot(x, y2, 'b-', label='y2')

# 合并图例到左下角
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='lower left')

# 显示图表
plt.show()

这样,图例就会被重新定位到左下角。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券