Python Pandas:如何将数据框列值设置为 X 轴标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38683709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:18:11  来源:igfitidea点击:

Python Pandas: How to set Dataframe Column value as X-axis labels

pythonpandasmatplotlibdataframe

提问by Volatil3

Say I have data in following format:

假设我有以下格式的数据:

Region   Men   Women
City1    10   5
City2    50   89

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

当我在 Dataframe 中加载它并绘制图形时,它会将索引显示为 X 轴标签而不是Region名称。如何在 X 轴上获取名称?

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

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

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

采纳答案by jedwards

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

由于您使用的是熊猫,看起来您可以将刻度标签直接传递给 DataFrame 的plot()方法。(文档)。(例如df.plot(..., xticks=<your labels>)

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

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

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

例如与(example)plt.xticks()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)

should force them to lay horizontally.

应该迫使它们水平放置。

回答by MaxU

plot.bar()method inherits its arguments from plot(), which has rotargument:

plot.bar()方法从plot()继承它的参数,它有rot参数:

from the docs:

从文档:

rot: int, default None

Rotation for ticks (xticks for vertical, yticks for horizontal plots)

rot: int, 默认无

刻度的旋转(垂直为 xticks,水平图为 yticks)

it also uses per default index as ticks for x axis:

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

use_index: boolean, default True

Use index as ticks for x axis

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>

alternatively you can set index explicitly - it might be useful for multi-level indexes (axes):

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

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

enter image description here

在此处输入图片说明

回答by nbenz

I had a lot of trouble finding an answer I really liked for this, the below function achieves it quite well, and is very adaptable,

我很难找到我真正喜欢的答案,下面的函数很好地实现了它,并且适应性很强,

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)

Below is an example of my result, though I set a new color for each value in a separate column in the dataframe

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

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

我的专栏标题为 ['A','B','C','D','E']