i have x-axis which is in terms of days (366 days Feb was taken as 29 days) but instead I want to convert it in terms of months (Jan – Dec). What should i do…
def plotGraph(): line, point = getXY() plt.plot(line['xlMax'], c='orangered', alpha=0.5, label = 'Minimum Temperature (2005-14)') plt.plot(line['xlMin'], c='dodgerblue', alpha=0.5, label = 'Minimum Temperature (2005-14)') plt.scatter(point['xsMax'].index, point['xsMax'], s = 10, c = 'maroon', label = 'Record Break Minimum (2015)') plt.scatter(point['xsMin'].index, point['xsMin'], s = 10, c = 'midnightblue', label = 'Record Break Maximum (2015)') ax1 = plt.gca() # Primary axes ax1.fill_between(line['xlMax'].index , line['xlMax'], line['xlMin'], facecolor='lightgray', alpha=0.25) ax1.grid(True, alpha = 1) for spine in ax1.spines: ax1.spines[spine].set_visible(False) ax1.spines['bottom'].set_visible(True) ax1.spines['bottom'].set_alpha(0.3) # Removing Ticks ax1.tick_params(axis=u'both', which=u'both',length=0) plt.show()
Advertisement
Answer
I think the quickest change might be to just set new ticks and tick labels at the starts of months; I found the conversion from day-of-the-year to month here, the first table:
import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() x = range(1,367) y = np.random.rand(len(range(1,367))) ax.plot(x,y) month_starts = [1,32,61,92,122,153,183,214,245,275,306,336] month_names = ['Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'] ax.set_xticks(month_starts) ax.set_xticklabels(month_names)
Note I assumed your days were numbered 1 to 366; if they are 0 to 365 you may have to change the range
.
But I think usually a better approach is to get your days into some sort of datetime
; this is more flexible and usually pretty smart. If say, your days were not confined to one year, it would be more complicated to associate day numbers with months.
This example uses datetime
instead of integers. The dates are plotted on the x-axis directly, and then the DateFormatter
and MonthLocator
from matplotlib.dates
are used to format the axis appropriately:
import datetime as dt import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np start = dt.datetime(2016,1,1) #there has to be a year given, even if it isn't plotted new_dates = [start + dt.timedelta(days=i) for i in range(366)] fig, ax = plt.subplots() x = new_dates y = np.random.rand(len(range(1,367))) xfmt = mdates.DateFormatter('%b') months = mdates.MonthLocator() ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(xfmt) ax.plot(x,y)