Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib Plot X, Y Line Plot Multiple Columns Fixed X Axis

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading