[英]Rotation x-ticks matplotlib
I can't seem to get the labels on the x-axis to rotate 90 degrees. 我似乎无法使x轴上的标签旋转90度。
Example df: df示例:
import pandas as pd
import matplotlib.pyplot as plt
d = ({
'A' : ['1','1','2','2','3','3','3'],
'B' : ['A','B','C','C','D','B','C'],
'C' : ['Foo','Bar','Foo','Bar','Cat','Bar','Cat'],
})
df = pd.DataFrame(data=d)
fig,ax = plt.subplots(figsize = (9,4))
df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar')
plt.show()
I have tried the basic: 我已经尝试了基本的:
plt.xticks(rotation = 90)
Also tried this but it returns an Attribute Error: 也尝试过此操作,但它返回属性错误:
df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar', rotation = 90)
I have got the labels to rotate through this: 我有标签可以旋转通过:
xticklabels = df.C.unique()
ax.set_xticklabels(xticklabels, rotation = 0)
But it returns incorrect ordering. 但是它返回不正确的顺序。 It just takes the values as they appear.
它只接受显示的值。 Rather than determining the appropriate label
而不是确定适当的标签
You can control the xticks labels through creating a subplot and configuring the label settings, like this: 您可以通过创建子图并配置标签设置来控制xticks标签,如下所示:
import pandas as pd
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
d = ({
'A' : ['1','1','2','2','3','3','3'],
'B' : ['A','B','C','C','D','B','C'],
'C' : ['Foo','Bar','Foo','Bar','Cat','Bar','Cat'],
})
df = pd.DataFrame(data=d)
udf = (df.assign(A=df.A.astype(int))
.pivot_table(index="C", columns="B", values="A",aggfunc='count')
.rename_axis(None)
.rename_axis(None,1))
udf.plot(kind='bar', ax=ax)
labels = ax.set_xticklabels(udf.index.values, rotation=0, fontsize=14)
One more thing, I think you need 0 degree rotation as the default is 90. 还有一件事,我认为您需要0度旋转,默认值为90度。
PS: Long chaining in pandas operations really eats away the readability. PS:大熊猫操作中的长链确实会吃掉可读性。
I run the code below to produce the labels with angle 0. I don't understand why there are two plots generated so I deleted the line fig,ax = plt.subplots()
我运行下面的代码以产生角度为0的标签。我不明白为什么生成了两个图,所以我删除了
fig,ax = plt.subplots()
import pandas as pd
import matplotlib.pyplot as plt
d = ({
'A' : ['1','1','2','2','3','3','3'],
'B' : ['A','B','C','C','D','B','C'],
'C' : ['Foo','Bar','Foo','Bar','Cat','Bar','Cat'],
})
df = pd.DataFrame(data=d)
#fig,ax = plt.subplots()
df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B",
values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar')
plt.xticks(rotation = 0)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.