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

Python 更改绘图的标签方向和图例位置,python,matplotlib,pandas,Python,Matplotlib,Pandas,我正在用Python中的pandas从CSV读取数据,绘制条形图。我将CSV读入数据框,并使用matplotlib打印它们 以下是我的CSV的外观: SegmentName Sample1 Sample2 Sample3 Loop1 100 100 100 Loop2 100 100 100 我绘制并将图例设置为外部 plt.figure() ax = res.plot(kind='bar'

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

以下是我的CSV的外观:

SegmentName    Sample1   Sample2   Sample3

Loop1          100       100       100

Loop2          100       100       100

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

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

plt.savefig("results.jpg")
但是,x轴标签是垂直的,因此我无法阅读文本。我在外面的传说也被切断了

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


设置标签时,请尝试使用“旋转”关键字。例如:

plt.xlabel('hi',rotation=90)
或者,如果需要旋转记号标签,请尝试:

plt.xticks(rotation=90)

至于图例的位置等,可能值得一看

您应该使用
matplotlib
API并调用
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')
要获得结果图,请执行以下操作:

或者,您可以调用
fig.autofmt_xdate()
以获得良好的倾斜效果,当然,您可以使用上面的
ax.set_xticklabels()


对于标签的旋转,您可以通过给
rot
参数指定度数,简单地告诉pandas为您旋转标签。 其他地方也回答了被切断的传说,如:


当然,我们需要将numpy作为np导入pandas作为pd从pandas导入*将matplotlib.pyplot作为plt导入包含到您的图像的链接,以便我们可以更新您的问题以包含图像。这是屏幕截图。似乎您试图在x轴上旋转标签,而不是标签,因为标签完全是另一个对象。你应该更新你的问题来澄清。情节也有一个论点。例如,水平方向的df.plot(kind='bar',rot=0)将旋转x轴上的标签,而不是轴标签,因此我认为这无法实现OP想要的。啊,我明白了。无论哪种方式,“rotation”关键字都是关键点-它可以传递到label函数中。更新答案。这是我的情节截图。从OP现在提供的图片来看,您的第一个解决方案似乎是正确的;他正在尝试旋转标签,而不是像他在问题中所写的那样旋转标签。我已经更新了我的答案,这应该可以帮助您找到答案并为您指出正确的方向。当我尝试使用ax=dataframe.plot()和“ax.setxticklabels(df.month_date,rotation=90)”时,我得到错误“numpy.ndarray”对象没有属性“setxticklabels”。我只想我的x轴标签旋转,使文本读取日期,从上到下垂直!这绝对是最好的<代码>腐烂就是我要找的
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')
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')
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')