简体   繁体   English

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

[英]rotate x-axis text and move y-labels to the top of axes (multiple y-axes)

In the following python code I'm plotting time datas and multiple y-values out of a dataframe. 在下面的python代码中,我正在绘制数据帧中的时间数据和多个y值。 Now I want to: - rotate the time values of the x-axis vertically - move all y-labels (y1-y4) to the top of the axis Does anyone have suggestions or solutions ? 现在我想: - 垂直旋转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()

在此输入图像描述

I have a solution for the first problem, and an ugly hack for the second. 我有第一个问题的解决方案,第二个问题是一个丑陋的黑客。

1) Rotate x-axis text 1)旋转x轴文本

You need to set this using the host.axis property, and then move the legend and xlabel down a bit to make room: 您需要使用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) Move y-labels to the top of axes 2)将y标签移动到轴的顶部

Nothing I tried here worked. 我在这里尝试的没有任何工作。 Specifically, I expected the following to work: 具体来说,我希望以下工作:

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

But the respective get_position command keeps returning (1.0, 0.5) , in which 0.5 is the middle of the axis. 但是相应的get_position命令保持返回(1.0, 0.5) get_position (1.0, 0.5) ,其中0.5是轴的中间。 For some reason the 'set' command simply won't stick. 由于某种原因,'set'命令根本不会坚持。 This is where the ugly hack comes in - adding blank lines below the label . 这是丑陋的黑客入侵的地方 - 在标签下方添加空白行 So where you set the label text, change to: 因此,在设置标签文本的位置,请更改为:

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)

Now we just need to set the vertical alignment of the labels, so that the blank lines take effect, adding some padding for better readability: 现在我们只需要设置标签的垂直对齐方式,使空行生效,添加一些填充以提高可读性:

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)

The above commands can be combined with the color and rotation settings, if you want more organized code, eg: 如果您想要更有条理的代码,上述命令可以与颜色和旋转设置结合使用,例如:

par1.axis['right'].label.set(color=p2.get_color(), rotation=-90, verticalalignment='bottom', pad=7)

Result: 结果:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM