更改标记的ticklabel方向和图例位置

use*_*971 8 python matplotlib pandas

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

以下是我的CSV的外观:

SegmentName    Sample1   Sample2   Sample3

Loop1          100       100       100

Loop2          100       100       100
Run Code Online (Sandbox Code Playgroud)
res = DataFrame(pd.read_csv("results.csv", index_col="SegmentName"))
Run Code Online (Sandbox Code Playgroud)

我绘制并将传奇设置为外部.

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

plt.savefig("results.jpg")
Run Code Online (Sandbox Code Playgroud)

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

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

在此输入图像描述

Dma*_*an2 8

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

plt.xlabel('hi',rotation=90)
Run Code Online (Sandbox Code Playgroud)

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

plt.xticks(rotation=90)
Run Code Online (Sandbox Code Playgroud)

至于传奇等的定位,可能值得一看紧凑的布局指南


Phi*_*oud 5

您应该使用API 并像这样matplotlib调用: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')
Run Code Online (Sandbox Code Playgroud)

得到结果图:

在此输入图像描述

或者,您可以要求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')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Mah*_*hdi 5

对于标签的旋转,您可以通过给出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')
Run Code Online (Sandbox Code Playgroud)