使用matlibplot卡住python多个twinx轴图

时间:2014-11-11 13:30:26

标签: python matplotlib

您好我正在尝试制作一个Y轴和4 X轴的图表

我不想制作单独的图表,并且想知道是否可以使用twinx()命令放置多个X轴。

我遇到的问题是我试图添加的最终轴最终出现在图表的两侧,我只想在左边。

from mpl_toolkits.axes_grid1 import host_subplot 
import mpl_toolkits.axisartist as AA 
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)

par1 = host.twinx()
par2 = host.twinx()

new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",axes=par2,offset=(60, 0))
par2.axis["right"].toggle(all=True)

host.set_xlabel("Y axis")
host.set_ylabel("X axis 1 on the left")
par1.set_ylabel("X axis 2 on the right") par2.set_ylabel("X axis 3 on the right")

par3 = host.twinx()

new_fixed_axis = par3.get_grid_helper().new_fixed_axis
par3.axis["left"] = new_fixed_axis(loc="left",axes=par3,offset=(-60, 0))
par3.axis["left"].toggle(all=True)

par3.set_ylabel("X axis 4 on the left")

p1, = host.plot([1,2,3,4],[1,2,3,4], label="1")
p2, = par1.plot([1,2,3,4],[2,2,2,2], label="2")
p3, = par2.plot([1,2,3,4],[3,3,2,1], label="3")
p4, = par3.plot([1,2,3,4],[1,1,2.5,3.5], label="4")

plt.show()

1 个答案:

答案 0 :(得分:1)

只需将可见性设置为False。

from mpl_toolkits.axes_grid1 import host_subplot 
import mpl_toolkits.axisartist as AA 
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(bottom=0.1, left=0.2, right=0.8, top=0.9)

par1 = host.twinx()
par2 = host.twinx()
par3 = host.twinx()
par3.axis["right"].set_visible(False)

new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",axes=par2,offset=(60, 0))

host.set_xlabel("Y axis")
host.set_ylabel("X axis 1 on the left")
par1.set_ylabel("X axis 2 on the right")
par2.set_ylabel("X axis 3 on the right")
par3.set_ylabel("X axis 4 on the left")


new_fixed_axis = par3.get_grid_helper().new_fixed_axis
par3.axis["left"] = new_fixed_axis(loc="left",axes=par3,offset=(-60, 0))


p1, = host.plot([1,2,3,4],[1,2,3,4], label="1")
p2, = par1.plot([1,2,3,4],[2,2,2,2], label="2")
p3, = par2.plot([1,2,3,4],[3,3,2,1], label="3")
p4, = par3.plot([1,2,3,4],[1,1,2.5,3.5], label="4")

plt.show()

顺便提一下,在提出这样的问题时,不要扭转对x轴和y轴的标准理解是有帮助的!另外,我必须添加一个subplot_adjust以使用mpl的标准设置查看整个数字。