Simon Lindgren
Simon Lindgren

Reputation: 2031

Sorting the x axis in matplotlib

Why does this code not plot the x-axis sorted by 'value'?

import pandas as pd
import matplotlib.pyplot as plt

# creating dataframe
df=pd.DataFrame()
df['name'] = [1,2,3]
df['value'] = [4,3,5]

# sorting dataframe
df.sort_values('value', ascending = False, inplace= True)

# plot
plt.scatter(df['value'],df['name'])
plt.show()

Upvotes: 5

Views: 26964

Answers (1)

andrew_reece
andrew_reece

Reputation: 21264

Given your choice of variable names, plus the seeming confusion surrounding the use of scatter plots, it seems like name may be a categorical variable that you'd like to plot on the x-axis, sorted by value.

If that's the case, I'd recommend initially plotting with df.index as the x-axis, and then changing the tick labels to name entries. Use reset_index() after sort_values to get the correct index ordering.

Both Pandas and Pyplot should be able to do this without additional modules, but I had some trouble getting tick labels to line up. Instead, I found Seaborn's pointplot() handled this job without any trouble:

# sort, then reset index
df = df.sort_values('value', ascending = False).reset_index(drop=True)

import seaborn as sns
ax = sns.pointplot(x=df.index, y=df.value)
ax.set_xlabel("Name")
ax.set_ylabel("Value")

# Use name column to label x ticks
_ = ax.set_xticklabels(df.name.astype(str).values)

[1]: https://i.sstatic.net/PX

Upvotes: 5

Related Questions