How to show month on x axis for only 12 data points

Viewed 143

I am able to create a plot with the name of the month when I have 365 data points with the following code:

y = np.random.normal(size=365)
x = np.array(range(len(y)))
plt.plot(x, y)
plt.xlabel('Month')
locator = mdates.MonthLocator()
fmt = mdates.DateFormatter('%b')
X = plt.gca().xaxis
X.set_major_locator(locator)
X.set_major_formatter(fmt)

Here is the result, which is exactly what I'm looking for: enter image description here

I would like to do the same thing but with only 12 data points (one for each month). If I just change the 365 to 12 (y = np.random.normal(size=12)), it looks like this:

enter image description here

How can I get it to show all the months in the x axis as in the first graph?

I tried passing arguments to MonthLocator (bymonth, bymonthday, interval) but none of them seemed to do what I'm looking for.

1 Answers
  • You only have 12 points, so MonthLocator won't work as desired.
  • It will be easier to set the x-axis as the month names with a list:
    • import calendar to get a list of month names, or type them manually, and then use x = calendar.month_abbr[1:]
import calendar  # part of the standard library
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(365)
y = np.random.normal(size=12)
x = calendar.month_abbr[1:]
plt.plot(x, y)
plt.xlabel('Month')

enter image description here

Related