简体   繁体   English

更改 Pandas / Matplotlib 直方图中标签的 x 轴顺序?

[英]Change x-axis order of labels in Pandas / Matplotlib histogram?

Suppose I have a Pandas dataframe with discrete values in a column.假设我有一个 Pandas dataframe 列中有离散值。

import pandas as pd

data = ['A']*2 + ['C']*3 + ['B']* 1
print(data)
# ['A', 'A', 'C', 'C', 'C', 'B']

my_df = pd.DataFrame({'mycolumn': data})
print(my_df)
#   mycolumn
# 0        A
# 1        A
# 2        C
# 3        C
# 4        C
# 5        B

I then create a histogram showing the frequency of those values.然后我创建了一个直方图来显示这些值的频率。 I use the Pandas built-in function hist() , which in turn relies on the Matplotlib histogram function.我使用 Pandas 内置的 function hist() ,它又依赖于 Matplotlib 直方图 function。

my_df.mycolumn.hist()

在此处输入图像描述

Now, how do I change the order of the labels on the X-axis to have a specific order?现在,如何更改 X 轴上标签的顺序以具有特定顺序? For example, I want the x-axis to have the labels in the specific order: C, A, B , not A, C, B as is shown.例如,我希望 x 轴具有特定顺序的标签: C, A, B ,而不是A, C, B如图所示。

Additionally, how do I change the y-axis to be integers rather than floats?此外,如何将 y 轴更改为整数而不是浮点数? The frequency values are discrete counts.频率值是离散计数。

You can use value_counts , loc to define order, and bar plot:您可以使用value_countsloc来定义顺序,以及bar plot:

my_df.mycolumn.value_counts().loc[['C', 'A', 'B']].plot.bar()

在此处输入图像描述

Solution to use integers on the y-axis:在 y 轴上使用整数的解决方案

from matplotlib.ticker import MaxNLocator

ax = my_df.mycolumn.value_counts().loc[['C', 'A', 'B']].plot.bar()

ax.yaxis.set_major_locator(MaxNLocator(integer=True))

在此处输入图像描述

You can create a sorter dict to sort your dataframe prior to plotting.您可以创建一个sorter字典来在绘图之前对您的 dataframe 进行排序。 For integers, you can use MaxNLocator :对于整数,您可以使用MaxNLocator

import pandas as pd
from matplotlib.ticker import MaxNLocator
fig, ax = plt.subplots()
data = ['A']*2 + ['C']*3 + ['B']* 1
my_df = pd.DataFrame({'mycolumn': data})
sorter = dict([(k, v) for (v,k) in enumerate(['C', 'A', 'B'])])
(my_df.assign(sorter=my_df['mycolumn'].map(sorter))
      .sort_values('sorter')['mycolumn'].value_counts().plot.bar(ax=ax))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM