Home > OS >  Matplotlib Plot X, Y Line Plot Multiple Columns Fixed X Axis
Matplotlib Plot X, Y Line Plot Multiple Columns Fixed X Axis

Time:02-19

I'm trying to plot a df with the x axis forced to 12, 1, 2 for (Dec, Jan, Feb) and I cannot see how to do this. Matplot keeps wanting to plot the x axis in the 1,2,12 order. My DF (analogs_re) partial columns for the example looks like this:

   Month      2000      1995      2009      2014      1994      2003  
0     12 -0.203835  0.580590  0.233124  0.490193  0.605808  0.016756   
1      1 -0.947029 -1.239794 -0.977004  0.207236  0.436458 -0.501948   
2      2 -0.059957  0.708626  0.111840  0.422534  1.051873 -0.149000

I need the y data plotted with x axis in 12, 1, 2 order as shown in the 'Month" column.

My code:

fig, ax = plt.subplots()
#for name, group in groups:
analogs_re.set_index('Month').plot(figsize=(10,5),grid=True)
analogs_re.plot(x='Month', y=analogs_re.columns[1:len(analogs_re.columns)])

enter image description here

CodePudding user response:

When you set Month as the x-axis then obviously it's going to plot it in numerical order (0, 1, 2, 3...), because a sequential series does not start with 12, then 1, then 2, ...

The trick is to use the original index as x-axis, then label those ticks using the month number:

fig, ax = plt.subplots()
analogs_re.drop(columns='Month').plot(figsize=(10,5), grid=True, ax=ax)
ax.set_xticks(analogs_re.index)
ax.set_xticklabels(analogs_re["Month"])

enter image description here

  • Related