Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Months as axis ticks

I would like to add monthly ticks to this plot - and it is currently showing ticks of 2015 and 2016 where i would like it to show Jan, Feb...Dec, Jan.

The index of the data that I have begins on 2015-01-01 and ends on 2015-12-31. The code I have so far is:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdate

plt.figure(figsize=(20,12))
#ax = plt.add_subplot(111)
plt.plot_date(list(max_group_by15.index), max_group_by15['Data_Value'])
plt.plot_date(list(min_group_by15.index), min_group_by15['Data_Value'])
plt.plot_date(list(min_group_by14.index), min_group_by14['Data_Value'], '-b')
plt.plot_date(list(max_group_by14.index), max_group_by14['Data_Value'], '-r')

plt.legend(['2015 Temp Exceed Prev High', '2015 Temp Below Prev Low', 'Min Temp 2005-2014', 'Max Temp 2005-2014'])
plt.gca().fill_between(min_group_by14.index, min_group_by14['Data_Value'], max_group_by14['Data_Value'], facecolor = 'blue', alpha =.25)



plt.xlabel('Month')
plt.ylabel('Degrees (Celsius)')
plt.title('Daily High and low temp in Ann Arbor area from 2005-2014')

locator = mdate.MonthLocator()
plt.gca().xaxis.set_major_locator(locator)

Produces this plot:

like image 765
ktj1989 Avatar asked Oct 04 '17 01:10

ktj1989


People also ask

How do I remove Y axis ticks?

To remove the ticks on the y-axis, tick_params() method has an attribute named left and we can set its value to False and pass it as a parameter inside the tick_params() function. It removes the tick on the y-axis.

How do I rotate Xticks in MatPlotLib?

MatPlotLib with Python To rotate tick labels in a subplot, we can use set_xticklabels() or set_yticklabels() with rotation argument in the method. Create a list of numbers (x) that can be used to tick the axes. Get the axis using subplot() that helps to add a subplot to the current figure.


2 Answers

Tough to try without your exact data, but I think you're simply missing a call to set_major_formatter.

import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Generate some random date-time data
numdays = 500
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)]
y = np.random.rand(numdays)

# Set the locator
locator = mdates.MonthLocator()  # every month
# Specify the format - %b gives us Jan, Feb...
fmt = mdates.DateFormatter('%b')


plt.plot(date_list,y)
X = plt.gca().xaxis
X.set_major_locator(locator)
# Specify formatter
X.set_major_formatter(fmt)
plt.show()

enter image description here

like image 65
saintsfan342000 Avatar answered Dec 14 '22 11:12

saintsfan342000


If it's just one year, it could be done like that:)

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan']
plt.xticks(np.linspace(0,365,13), months)
like image 27
powtostream Avatar answered Dec 14 '22 11:12

powtostream