在matplotlib中的x轴上使用3个图对齐/旋转文本标签 [英] Aligning/rotating text labels on x axis in matplotlib with 3 plots
问题描述
如何在此处将文本标签与图中的x记号对齐?我正在使用host.set_xticklabels(labels,rotation ='vertical'),但这似乎不起作用. 我的标签是句子,有些标签可能比其他标签小/大,例如木乃伊返回第2部分"-如何在x轴下方填充空格以适应此问题?
How should I align the text labels against the x tickers in the graph here ? I am using host.set_xticklabels(labels,rotation='vertical') , but that doesnt seem to work . My labels are sentences and some could be smaller/larger than others, like "The mummy returns part 2" - How do I pad a space below the x axis to accommodate this ?
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
path='/home/project/df.csv'
df=pd.read_csv(path,sep=',',header='infer')
xs =range(0,101)
ys =list(df['B'].ix[0:100])
zs=list(df['C'].ix[0:100])
ws=list(df['D'].ix[0:100])
if 1:
host = host_subplot(111, axes_class=AA.Axes)
p1, = host.plot(xs, ys, label='B')
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
axes=par2,
offset=(offset, 0))
par2.axis["right"].toggle(all=True)
host.set_xlim(min(xs), max(xs))
host.set_ylim(100, max(ys))
host.set_xlabel("A")
host.set_ylabel("B")
par1.set_ylabel("C")
par2.set_ylabel("D")
p2, = par1.plot(xs, ws, label='C',color='red')
p3, = par2.plot(xs, zs, label='D',color='green')
for tl in par1.get_yticklabels():
tl.set_color('red')
for tl in par2.get_yticklabels():
tl.set_color('green')
for tl in par1.get_yticklabels():
tl.set_color('r')
for tl in par2.get_yticklabels():
tl.set_color('g')
host.legend()
host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())
start, end, stepsize=0,len(df)-1,3
host.xaxis.set_ticks(np.arange(start, end, stepsize))
labels=list(df['A'])[0::stepsize]
host.set_xticklabels(labels,rotation='vertical')
plt.tight_layout()
plt.draw()
plt.show()
我需要对齐图片中的黑色"质量.
I need to align the "black" mass as in the picture.
我在这里的示例中尝试了建议 python在xaxis上旋转值不会重叠-plt.xticks(x,标签,rotation ='vertical')等等,但这是行不通的.
I tried the suggestions in the example here python rotate values on xaxis to not overlap - plt.xticks(x, labels, rotation='vertical') , and more, but that did not work.
编辑-: 从下面的Kazemakaze反馈中,这是我尝试的-: f,host = plt.subplots() #host = host_subplot(111,axes_class = AA.Axes) 但是我也必须修改其余的代码.您能提供一个适用于Twinx轴的示例吗?
Edit -: From Kazemakaze's feedback below, here's what I tried -: f,host= plt.subplots() #host = host_subplot(111, axes_class=AA.Axes) but I must adapt the rest of the code as well . Can you provide an example with twinx axis where this works ?
我正在使我的代码适应此带有twinx的辅助轴():如何添加图例?,旋转现在可以了,尽管在辅助轴上需要一些指针.
I am adapting my code to this Secondary axis with twinx(): how to add to legend? and the rotation works now, need some pointers on the secondary axis though.
推荐答案
这是我解决的方法-不旋转的问题的确是host_subplot
,并且在使用plt.subplot
Here's how I solved it- the problem of not rotating was indeed with host_subplot
and it works correctly when using plt.subplot
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
path='/home/project/df.csv'
df=pd.read_csv(path,sep=',',header='infer')
xs =range(0,101)
ys =list(df['B'].ix[0:100])
zs=list(df['C'].ix[0:100])
ws=list(df['D'].ix[0:100])
def make_patch_spines_invisible(ax):
ax.set_frame_on(True)
ax.patch.set_visible(False)
for sp in ax.spines.itervalues():
sp.set_visible(False)
def three_way_plot(xs,ys,ws,zs,category):
fig, host = plt.subplots()
fig.subplots_adjust(right=0.6)
par1 = host.twinx()
par2 = host.twinx()
par2.spines["right"].set_position(("axes", 1.1))
p1, = host.plot(xs, ys, "blue", linewidth=2.0, label="B")
p2, = par1.plot(xs, ws, "r-", label="C")
p3, = par2.plot(xs, zs, "g-", label="D")
host.set_xlim(min(xs), max(xs))
host.set_ylim(min(ys), max(ys) + 200)
par1.set_ylim(min(ws), max(ws) + 200)
par2.set_ylim(min(zs), max(zs))
host.set_xlabel("A", fontsize=14)
host.set_ylabel("B", fontsize=14)
par1.set_ylabel("C", fontsize=14)
par2.set_ylabel("D", fontsize=14)
host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())
lines = [p1, p2, p3]
labels = ["mary had a little lamb","The mummy returns","Die another day","Welcome back"]*25
start, end, step_size = 0, len(df) - 1, 4
host.set_xticks(np.arange(start, end, step_size))
host.set_xticklabels(labels, rotation='vertical', fontsize=10)
host.legend(lines, [l.get_label() for l in lines])
plt.tight_layout()
plt.show()
three_way_plot(xs,ys,ws,zs,"category")
当然,我掩盖了数据的True标签.
Ofcourse, I masked the True labels of the data.
这篇关于在matplotlib中的x轴上使用3个图对齐/旋转文本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!