[英]How do I order my x-axis on pandas bar plot?
Been struggling for a few days on a uni project I have to hand in in a week.在一个我必须在一周内提交的 uni 项目上挣扎了几天。 I'm working with a dataset (using pandas, mostly) and I have to anayze information about mountain expeditions.
我正在使用数据集(主要使用 pandas),我必须分析有关山地探险的信息。 My bar plots work fine but I still have the same issue every time: my x-axis is not in growing order, which isn't of the highest importance but it still bothers me.
我的条形图工作正常,但每次我仍然遇到同样的问题:我的 x 轴没有按增长顺序排列,这不是最重要的,但它仍然困扰着我。 I have been looking everywhere online but I can't find anything to fix my issue.
我一直在网上到处寻找,但找不到任何东西可以解决我的问题。 Here's my line of code:
这是我的代码行:
expeditions['members'].value_counts().plot.bar(figsize=(12,8))
The column members just contains integers and represents how many people took part in each expedition.列成员只包含整数,表示每次探险有多少人参加。 But here is what I get:
但这是我得到的:
How do I order the x-axis in growing order?如何按增长顺序排列 x 轴? I realize this must be pretty simple but I just can't figure out how to do it;
我意识到这一定很简单,但我就是不知道该怎么做; and I have the same issue with all my other graphs...
我对所有其他图表都有同样的问题......
Thanks for the help!谢谢您的帮助!
Try sorting the index like this:尝试像这样对索引进行排序:
expeditions['members'].value_counts().sort_index().plot.bar(figsize=(12,8))
value_counts
sorts the values by descending frequencies by default. value_counts
默认按频率降序对值进行排序。 Disable sorting using sort=False
:使用
sort=False
禁用排序:
expeditions['members'].value_counts(sort=False).plot.bar(figsize=(12,8))
Or sort the index prior to plotting:或者在绘图之前对索引进行排序:
expeditions['members'].value_counts().sort_index().plot.bar(figsize=(12,8))
Just for illustration仅作说明
You need to sort_values / value_counts
or value_counts / sort_index
before your plot as suggested by the two previous answers of @Bashton and @mozway :正如@Bashton 和 @mozway 的前两个答案所建议的那样,您需要在 plot 之前对
sort_values / value_counts
或value_counts / sort_index
进行排序:
import pandas as pd
import matplotlib.pyplot as plt
# Sample
expeditions = pd.DataFrame({'members': np.random.randint(1, 10, 100)})
expeditions['members'].sort_values().value_counts(sort=False) \
.plot.bar(figsize=(12, 8), legend=False)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.