python绘图创建两个坐标轴 共享一个x轴

在Matplotlib中,可以使用twiny()或者twinx()方法创建一个共享一条轴线的第二个坐标轴,从而实现绘制两个坐标轴的效果

import matplotlib.pyplot as plt
import numpy as np

# 创建一些示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 绘制第一个坐标轴
fig, ax1 = plt.subplots()

ax1.plot(x, y1, label='Sin(x)', color='blue')
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Sin(x)', color='blue')
ax1.tick_params('y', colors='blue')

# 创建第二个坐标轴,共享X轴
ax2 = ax1.twinx()
ax2.plot(x, y2, label='Cos(x)', color='red')
ax2.set_ylabel('Cos(x)', color='red')
ax2.tick_params('y', colors='red')

# 添加图例
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='upper right')

# 显示图形
plt.show()

在这个例子中,ax1是第一个坐标轴,ax2是共享X轴的第二个坐标轴。使用ax1.twinx()创建ax2,并通过ax2.set_ylabel()设置第二个坐标轴的Y轴标签。最后,使用ax2.legend()将两个坐标轴的图例合并显示。

问题

1、发现上面代码运行,两个坐标轴的图例互相之间被覆盖了

解决方法:

import matplotlib.pyplot as plt
import numpy as np

# 创建一些示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建第一个坐标轴
fig, ax1 = plt.subplots()
line1, = ax1.plot(x, y1, label='Sin(x)', color='blue')
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Sin(x)', color='blue')
ax1.tick_params('y', colors='blue')

# 创建第二个坐标轴,共享X轴
ax2 = ax1.twinx()
line2, = ax2.plot(x, y2, label='Cos(x)', color='red')
ax2.set_ylabel('Cos(x)', color='red')
ax2.tick_params('y', colors='red')

# 合并图例
lines = [line1, line2]
labels = [line.get_label() for line in lines]
ax1.legend(lines, labels, loc='upper right')

# 显示图形
plt.show()
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值