本文介绍了Python Pandas:如何将“数据框列"值设置为X轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下格式的数据:

Say I have data in following format:

Region   Men   Women
City1    10   5
City2    50   89

当我将其加载到数据框和绘图图中时,它将索引显示为X轴标签,而不是Region名称.如何在X轴上获取名称?

When I load it in Dataframe and plot graph, it shows index as X-axis labels instead of Region name. How do I get names on X-axis?

到目前为止,我已经尝试过:

So far I tried:

import pandas as pd
import matplotlib.pyplot as plt    
plt.style.use('ggplot')
ax = df[['Men','Women']].plot(kind='bar', title ="Population",figsize=(15,10),legend=True, fontsize=12)
ax.set_xlabel("Areas",fontsize=12)
ax.set_ylabel("Population",fontsize=12)
plt.show()

当前它显示x个刻度为0,1,2..

Currently it shows x ticks as 0,1,2..

推荐答案

由于您使用的是熊猫,因此您似乎可以将对勾标签直接传递给DataFrame的plot()方法. (文档). (例如df.plot(..., xticks=<your labels>))

Since you're using pandas, it looks like you can pass the tick labels right to the DataFrame's plot() method. (docs). (e.g. df.plot(..., xticks=<your labels>))

此外,由于熊猫使用matplotlib,因此您可以通过这种方式控制标签.

Additionally, since pandas uses matplotlib, you can control the labels that way.

例如,使用 plt.xticks() (示例) ax.set_xticklabels()

For example with plt.xticks() (example) or ax.set_xticklabels()

关于旋转,后两种方法允许您将旋转参数与标签一起传递.像这样:

Regarding the rotation, the last two methods allow you to pass a rotation argument along with the labels. So something like:

ax.set_xticklabels(<your labels>, rotation=0)

应迫使它们水平放置.

这篇关于Python Pandas:如何将“数据框列"值设置为X轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 01:12