Python Pandas:如何将Dataframe Column值设置为X轴标签

时间:2016-07-31 11:54:14

标签: python pandas matplotlib dataframe

说我有以下格式的数据:

Region   Men   Women
City1    10   5
City2    50   89

当我在Dataframe和plot graph中加载它时,它将索引显示为X轴标签而不是Region名称。如何在X轴上获取名称?

到目前为止,我试过了:

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..

3 个答案:

答案 0 :(得分:10)

由于你正在使用pandas,看起来你可以将tick标签直接传递给DataFrame的plot()方法。 (docs)。 (例如df.plot(..., xticks=<your labels>)

此外,由于pandas使用matplotlib,您可以通过这种方式控制标签。

例如plt.xticks() (example)ax.set_xticklabels()

关于旋转,最后两种方法允许您将旋转参数与标签一起传递。如下所示:

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

应该强迫它们水平放置。

答案 1 :(得分:7)

plot.bar()方法从plot()继承其参数,该参数具有rot参数:

来自文档:

  

腐烂:int,默认无

     

旋转刻度线(xticks垂直,   yticks for horizo​​ntal plot)

它还使用每个默认索引作为x轴的刻度:

  

use_index :布尔值,默认为True

     

将索引用作x轴的刻度

In [34]: df.plot.bar(x='Region', rot=0, title='Population', figsize=(15,10), fontsize=12)
Out[34]: <matplotlib.axes._subplots.AxesSubplot at 0xd09ff28>

或者您可以显式设置索引 - 它可能对多级索引(轴)有用:

df.set_index('Region').plot.bar(rot=0, title='Population', figsize=(15,10), fontsize=12)

enter image description here

答案 2 :(得分:0)

为此我很难找到一个我真正喜欢的答案,下面的功能可以很好地实现它,并且适应性很强,

def plot_vals_above_titles(data_frame, columns):
    import random
    y_vals = {}

    fig = plt.figure()
    plt.grid(True)

    for index, row in data_frame.iterrows():
        x_coord = 0

        for col in columns:
            # add some jitter to move points off vertical line
            jitter = random.uniform(-0.1,.1)
            x_coord += jitter

            plt.scatter(
                x = x_coord,
                y = row[col]
                )

            x_coord -= jitter
            x_coord+=1

    # rename the xticks with column names
    x_vals = range(0, len(columns))
    plt.xticks(x_vals, columns)

下面是我的结果的一个示例,尽管我在数据帧的单独列中为每个值设置了新颜色

My columns were titled ['A','B','C','D','E']