更改p的标签方向和图例位置

2024-05-19 13:09:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python中的pandas从CSV读取数据,绘制条形图。我将CSV读入DataFrame并使用matplotlib绘制它们。

以下是我的CSV的外观:

SegmentName    Sample1   Sample2   Sample3

Loop1          100       100       100

Loop2          100       100       100

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

我绘制并将图例设置为外部。

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

plt.savefig("results.jpg")

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

我可以把记号标签的方向改成水平,然后调整整个图形,使图例可见吗?

enter image description here


Tags: csvdataframepandasmatplotlib绘制resplt标签
3条回答

设置标签时尝试使用“rotation”关键字。E、 g.:

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

或者,如果需要旋转记号标签,请尝试:

plt.xticks(rotation=90)

至于传说的位置等,可能值得一看tight layout guide

您应该使用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')

要获得结果图:

enter image description here

或者,您可以调用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

对于标签的旋转,只需给rot参数指定度数,就可以告诉pandas为您旋转标签。 被切断的传说也在别处得到了回答,比如here

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')

相关问题 更多 >