简体   繁体   中英

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. I'm working with a dataset (using pandas, mostly) and I have to anayze information about mountain expeditions. 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. 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? 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. Disable sorting using 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 :

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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