pandas 更改绘图的刻度标签方向和图例位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18098061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:04:09  来源:igfitidea点击:

Change the ticklabel orientation and legend position of plot

pythonmatplotlibpandas

提问by user2450971

I am plotting a bar graph by reading data from a CSV using pandas in Python. I read a CSV into a DataFrameand plot them using matplotlib.

我正在通过使用 Python 中的 Pandas 从 CSV 读取数据来绘制条形图。我将 CSV 读入 aDataFrame并使用 matplotlib 绘制它们。

Here is how my CSV looks like:

这是我的 CSV 的样子:

SegmentName    Sample1   Sample2   Sample3

Loop1          100       100       100

Loop2          100       100       100


res = DataFrame(pd.read_csv("results.csv", index_col="SegmentName"))

I plot and set the legend to be outside.

我绘制并将图例设置在外面。

plt.figure()
ax = res.plot(kind='bar')
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.savefig("results.jpg")

However, the x-axis ticklabels are orientated vertically and hence I can't read the text. Also my legend outside is cut off.

但是,x 轴刻度标签是垂直方向的,因此我无法阅读文本。我在外面的传说也被切断了。

Can I change the orientation of the ticklabels to be horizontal, and then adjust the entire figure so that the legend is visible?

我可以将刻度标签的方向更改为水平方向,然后调整整个图形以使图例可见吗?

enter image description here

在此处输入图片说明

回答by Dman2

Try using the 'rotation' keyword when you set the label. E.g.:

设置标签时尝试使用 'rotation' 关键字。例如:

plt.xlabel('hi',rotation=90)

Or if you need to rotate the tick labels, try:

或者,如果您需要旋转刻度标签,请尝试:

plt.xticks(rotation=90)

As for the positioning of the legend etc., it is probably worth taking a look at the tight layout guide

至于图例的定位等,大概值得一看的紧的布局指南

回答by Mahdi

For the rotation of the labels, you can simply tell pandas to rotate it for you by giving the number of degrees to the rotargument. The legends being cut off is answered elsewhere as well, like here:

对于标签的旋转,您可以通过为rot参数提供度数来简单地告诉Pandas为您旋转它。被切断的传说也在其他地方得到了回答,比如这里

df = pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
                              orient='index', columns=['one', 'two', 'three'])
ax = df.plot(kind='bar', rot=90)
lgd = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
fig.savefig("results.jpg", bbox_extra_artists=(lgd,), bbox_inches='tight')

回答by Phillip Cloud

You should use the matplotlibAPI and call ax.set_xticklabels(res.index, rotation=0)like so:

您应该使用matplotlibAPI 并ax.set_xticklabels(res.index, rotation=0)像这样调用:

index = Index(['loop1', 'loop2'], name='segment_name')
data = [[100] * 3, [100] * 3]
columns = ['sample1', 'sample2', 'sample3']
df = DataFrame(data, index=index, columns=columns)

fig, ax = subplots()
df.plot(ax=ax, kind='bar', legend=False)
ax.set_xticklabels(df.index, rotation=0)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
fig.savefig('results.png', bbox_inches='tight')

to get the resulting plot:

得到结果图:

enter image description here

在此处输入图片说明

Alternatively you can call fig.autofmt_xdate()for a nice tilted effect, which you can of course tinker with with the above (and more general) ax.set_xticklabels():

或者,您可以调用fig.autofmt_xdate()一个很好的倾斜效果,您当然可以对上述(以及更一般的)进行修改ax.set_xticklabels()

fig, ax = subplots()
df.plot(ax=ax, kind='bar', legend=False)
fig.autofmt_xdate()
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
fig.savefig('results-tilted.png', bbox_inches='tight')

enter image description here

在此处输入图片说明