我写了一个基于matplotlib的Python脚本,它根据公共时间线生成曲线。在我的绘图中共享相同x轴的曲线数量可以在1到6之间变化,具体取决于用户选项。绘制的每个数据使用不同的y刻度,并且需要不同的轴进行绘制。因此,我可能需要在我的绘图右侧绘制最多5个不同的Y轴。当我添加新的时,我在其他帖子中找到了偏移轴位置的方法,但我还有两个问题:
我无法分享我的整个代码,因为它太大了,但我从this example的代码中派生出来。我通过添加一个额外的绘图和一个额外的轴来修改该示例,以更接近地匹配我的脚本中要执行的操作。
import matplotlib.pyplot as plt
def make_patch_spines_invisible(ax):
ax.set_frame_on(True)
ax.patch.set_visible(False)
for sp in ax.spines.values():
sp.set_visible(False)
fig, host = plt.subplots()
fig.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
par3 = host.twinx()
# Offset the right spine of par2. The ticks and label have already been
# placed on the right by twinx above.
par2.spines["right"].set_position(("axes", 1.2))
# Having been created by twinx, par2 has its frame off, so the line of its
# detached spine is invisible. First, activate the frame but make the patch
# and spines invisible.
make_patch_spines_invisible(par2)
# Second, show the right spine.
par2.spines["right"].set_visible(True)
par3.spines["right"].set_position(("axes", 1.4))
make_patch_spines_invisible(par3)
par3.spines["right"].set_visible(True)
p1, = host.plot([0, 1, 2], [0, 1, 2], "b-", label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], "r-", label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], "g-", label="Velocity")
p4, = par3.plot([0,0.5,1,1.44,2],[100, 102, 104, 108, 110], "m-", label="Acceleration")
host.set_xlim(0, 2)
host.set_ylim(0, 2)
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")
par3.set_ylabel("Acceleration")
host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())
par3.yaxis.label.set_color(p4.get_color())
tkw = dict(size=4, width=1.5)
host.tick_params(axis='y', colors=p1.get_color(), **tkw)
par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
par3.tick_params(axis='y', colors=p4.get_color(), **tkw)
host.tick_params(axis='x', **tkw)
lines = [p1, p2, p3, p4]
host.legend(lines, [l.get_label() for l in lines])
# fourth y axis is not shown unless I add this line
plt.tight_layout()
plt.show()
当我运行这个时,我获得了以下情节:output from above script
在此图像中,上面的问题2意味着我希望y轴标签“温度”,“速度”,“加速度”直接绘制在每个相应的轴下方。
在此先感谢您的帮助。
问候,
L.
对我有用的是对欧内斯特使用文本的建议的重要性(如同一行一样)
host.text(1.2,0,“Velocity”,ha =“left”,va =“top”,rotation = 90,transform = host.transAxes))
而不是试图控制标签位置。