在pylab中同时使用上下坐标轴(例如,单位不同)

5 投票
2 回答
9863 浏览
提问于 2025-04-15 11:08

我正在尝试使用pylab/matplotlib制作一个图表,但我的x轴有两种不同的单位。所以我希望这个图表能有两个不同的x轴,一个在上面,一个在下面。(比如,一个是英里,一个是公里之类的。)

就像下面的图表(不过我想要多个X轴,但这其实没关系。)

多个轴的图表

有没有人知道用pylab能不能做到这一点?

2 个回答

1

在“原始”框架旁边添加多个坐标轴,就像示例图片中看到的那样,可以通过使用 twinx 来添加额外的坐标轴,并配置它们的 spines 属性。

我觉得这看起来和示例图片非常相似:

图 1

import matplotlib.pyplot as plt
import numpy as np

# Set font family
plt.rcParams["font.family"] = "monospace"

# Get figure, axis and additional axes
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twinx()
ax4 = ax1.twinx()

# Make space on the right for the additional axes
fig.subplots_adjust(right=0.6)

# Move additional axes to free space on the right
ax3.spines["right"].set_position(("axes", 1.2))
ax4.spines["right"].set_position(("axes", 1.4))

# Set axes limits
ax1.set_xlim(0, 7)
ax1.set_ylim(0, 10)
ax2.set_ylim(15, 55)
ax3.set_ylim(200, 600)
ax4.set_ylim(500, 750)

# Add some random example lines
line1, = ax1.plot(np.random.randint(*ax1.get_ylim(), 8), color="black")
line2, = ax2.plot(np.random.randint(*ax2.get_ylim(), 8), color="green")
line3, = ax3.plot(np.random.randint(*ax3.get_ylim(), 8), color="red")
line4, = ax4.plot(np.random.randint(*ax4.get_ylim(), 8), color="blue")

# Set axes colors
ax1.spines["left"].set_color(line1.get_color())
ax2.spines["right"].set_color(line2.get_color())
ax3.spines["right"].set_color(line3.get_color())
ax4.spines["right"].set_color(line4.get_color())

# Set up ticks and grid lines
ax1.minorticks_on()
ax2.minorticks_on()
ax3.minorticks_on()
ax4.minorticks_on()
ax1.tick_params(direction="in", which="both", colors=line1.get_color())
ax2.tick_params(direction="in", which="both", colors=line2.get_color())
ax3.tick_params(direction="in", which="both", colors=line3.get_color())
ax4.tick_params(direction="in", which="both", colors=line4.get_color())
ax1.grid(axis='y', which='major')

plt.show()

5

这可能有点晚了,但看看这样的内容是否能帮到你:

http://matplotlib.sourceforge.net/examples/axes_grid/simple_axisline4.html

撰写回答