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!
CodePudding user response:
Try sorting the index like this:
expeditions['members'].value_counts().sort_index().plot.bar(figsize=(12,8))
CodePudding user response:
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))
CodePudding user response:
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()