0
$\begingroup$

I need to display months on x axis of a plot instead of the indexes number of a data frame that goes from 1 to 365, which they represent the number of day of the year. So instead of an x-axis which goes from 1 to 365, I want to display it as "Jan", "Feb" and so on, without losing the structure of the plot.

Here is the main structure of my data frame:

    Month   Day Max_Data    Min_Data    MonthDay
1   1       1   1.1        -13.3        1-1
2   1       2   3.9        -12.2        1-2
3   1       3   3.9        -6.7         1-3
4   1       4   4.4        -8.8         1-4
5   1      5    2.8        -15.5        1-5

I am currently plotting using:

plt.scatter(data_2015.index, data_2015['Max_Data'], marker='^', color='green',s=40, alpha=1.0)

And if I changed data_2015.index to Month the graph will plot a different a completely wrong values, as they 28, 30 or 31 rows for each month.

So what is the way to convert indexes into month and display them into the x axis of a plot?

$\endgroup$
1
$\begingroup$

You will have to tweak the xaxis locator

e.g. For your sample data -

Month,Day,Max_Data,Min_Data,MonthDay
1,1,1.1,-13.3,1-1
1,2,3.9,-12.2,1-2
1,3,3.9,-6.7,1-3
1,4,4.4,-8.8,1-4
1,52.8,-15.5,1-5

import pandas as pd, numpy as np, seaborn as sns, matplotlib.pyplot as plt

data_2015 = pd.read_csv("/content/tst.csv")
plt.scatter(data_2015.index, data_2015['Max_Data'], marker='^', color='green',s=40, alpha=1.0,)

import matplotlib.ticker as mticker
plt.gca().xaxis.set_major_locator(mticker.FixedLocator(np.arange(len(data_2015.index))))
plt.gca().xaxis.set_major_formatter(mticker.FixedFormatter(np.array(['Jan','Feb','Mar','Jan','Feb'])))

Output

enter image description here

$\endgroup$
0
$\begingroup$

Actually I found a better solution by doing simply the following:

month_starts = [0,31,60,91,121,152,182,213,244,274,305,335]
month_names = ['Jan','Feb','Mar','Apr','May','Jun',
               'Jul','Aug','Sep','Oct','Nov','Dec'] 
plt.gca().set_xticks(month_starts)
plt.gca().set_xticklabels(month_names)

from this post on stack overflow.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.