matplotlib plot monthly count in order

Question:

How do I plot a monthly count of events with the right order in the x-axis?

I have several dataframes like the below (this is an example):

df = pd.DataFrame({'Month': [5, 6, 8, 9, 1, 2, 3, 4, 7, 10, 11, 12], 'Count': [3, 1, 6, 1, 0, 0, 0, 0, 0, 0, 0, 0]})

where I have counts of events per month, not in order. My aim is to line-plot a monthly count, and when I do

fig, ax = plt.subplots(1,1)
ax.grid(color='gray', linestyle='-', linewidth=0.1)
plt.setp(ax, xticks=np.arange(1, 13, step=1))
ax.plot(df.Month, df.Count, marker='o')

it plots in the order of the df.Month. This is not what I want:

enter image description here

What I want in magenta (ignore the markers…)

enter image description here

How do I get this plot?

Asked By: nahusznaj

||

Answers:

Using sort_values:

df = df.sort_values('Month')

or directly plotting from pandas:

import matplotlib.ticker as mticker

fig, ax = plt.subplots(1,1)
df.sort_values('Month').plot(
    x='Month', y='Count', 
    marker='o', legend=False, ax=ax
)
ax.grid(color='gray', linestyle='-', linewidth=0.1)
ax.xaxis.set_major_locator(mticker.MultipleLocator())

Output:

enter image description here

Answered By: BigBen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.