将x轴文本旋转并将y标签移动到轴的顶部(多个y轴)

3
在以下Python代码中,我正在绘制来自数据帧的时间数据和多个y值。 现在我想要: - 将x轴的时间值垂直旋转 - 将所有y标签(y1-y4)移动到坐标轴顶部 有人有建议或解决方案吗?
import pandas as pd
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

data = {'time':['00:00:00','18:00:00','23:59:00'],
          'y1': [1,2,3],'y2': [4,5,6],'y3': [7,8,9],'y4': [10,11,12]}

df=pd.DataFrame(data,columns=['time','y1','y2','y3','y4'])
df['time']=pd.to_datetime(df['time'],format='%H:%M:%S')

host=host_subplot(111,axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)
par1=host.twinx()
par2=host.twinx()
par3=host.twinx()
offset1=40
offset2=80 
new_fixed_axis=par2.get_grid_helper().new_fixed_axis

par2.axis['right']=new_fixed_axis(loc='right',axes=par2,offset=(offset1,0))
par2.axis['right'].toggle(all=True)
par3.axis['right']=new_fixed_axis(loc='right',axes=par3,offset=(offset2,0))
par3.axis['right'].toggle(all=True)

host.set_xlabel('Time')
host.set_ylabel('y1')
par1.set_ylabel('y2')
par2.set_ylabel('y3')
par3.set_ylabel('y4')

p1,=host.plot(df['time'],df['y1'])
p2,=par1.plot(df['time'],df['y2'])
p3,=par2.plot(df['time'],df['y3'])
p4,=par3.plot(df['time'],df['y4'])

host.set_ylim(0,5)
par1.set_ylim(0,8)
par2.set_ylim(0,10)
par3.set_ylim(0,15)

host.legend(loc='upper left',bbox_to_anchor=(0,-.15),ncol=4) 
host.axis['left'].label.set_color(p1.get_color())
host.axis["left"].label.set_rotation(90)

par1.axis['right'].label.set_color(p2.get_color())
par1.axis["right"].label.set_rotation(-90)

par2.axis['right'].label.set_color(p3.get_color())
par2.axis["right"].label.set_rotation(-90)

par3.axis['right'].label.set_color(p4.get_color())
par3.axis["right"].label.set_rotation(-90)

plt.draw()
plt.show()

enter image description here


我遇到了同样的问题。你找到了解决这个问题的方法吗? - Stefan Falk
1个回答

0

我有第一个问题的解决方案,和第二个问题的一个丑陋的hack。

1) 旋转x轴文本

您需要使用host.axis属性来设置此内容,然后将图例和xlabel向下移动一点以腾出空间:

host.legend(loc='upper left',bbox_to_anchor=(0,-.3),ncol=4)  # Lower legend a bit
host.axis["bottom"].label.set_pad(50)  # Lower x-label a bit
host.axis["bottom"].major_ticklabels.set(  # This is the actual rotation command
    rotation=90, verticalalignment='center', horizontalalignment='right', pad=-2)

2) 将y轴标签移动到坐标轴顶部

我尝试过的所有方法都没有奏效。具体来说,我期望以下方法可以实现:

par1.axis["right"].label.set_position((1.0, 1.0))

但是相应的get_position命令一直返回(1.0, 0.5),其中0.5是轴的中心。由于某种原因,“set”命令就是不起作用。这就是丑陋的hack出现的地方 - 在标签下面添加空行。所以在设置标签文本的地方,改为:

new_line_pos_fix = ''.join(['\n'] * 9)  # 9 is the number of blank lines; change as needed
host.set_ylabel('y1' + new_line_pos_fix)
par1.set_ylabel('y2' + new_line_pos_fix)
par2.set_ylabel('y3' + new_line_pos_fix)
par3.set_ylabel('y4' + new_line_pos_fix)

现在我们只需要设置标签的垂直对齐方式,以便空白行生效,并添加一些填充以提高可读性:
host.axis['right'].label.set(verticalalignment='bottom', pad=7)
par1.axis['right'].label.set(verticalalignment='bottom', pad=7)
par2.axis['right'].label.set(verticalalignment='bottom', pad=7)
par3.axis['right'].label.set(verticalalignment='bottom', pad=7)

以上命令可以与颜色和旋转设置相结合,以获得更有组织的代码,例如:
par1.axis['right'].label.set(color=p2.get_color(), rotation=-90, verticalalignment='bottom', pad=7)

结果:

enter image description here


亲爱的Shovalt,抱歉我回复晚了!<br> - SKYPY
没问题,希望这能在某种程度上有所帮助。 - Shovalt
我想写:<br> 亲爱的Shovalt,抱歉回复晚了!<br> 非常感谢您提供的解决方案,两个都完美地运行了,您真是太棒了!!!<br> 我只有一个评论:<br> 2) 将y轴标签移到坐标轴顶部:<br> 我已经更改为:<br> host.axis['left'].label.set(verticalalignment='bottom', pad=7) <br> - SKYPY

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接