tktktk0711
tktktk0711

Reputation: 1694

python2.7: how to plot the value of the grid line of x-axis in the figure

Hi I ploted two lines in a figure, the x-axis is the datetime from '2016-04-01' to '2017-03-31', the value showed on the grid line width is one month, namely 30 days, but I want to the grid line of width is 50 days. I mean that I want to show the date value of x-axis is: 2016-04-01, 2016-05-21,2016-07-10,2016-10-18,2016-12-07,2017-01-26,2017-03-17.

T

My code is following:

import seaborn as sn
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


sn.set_style("darkgrid")
xfmt = mdates.DateFormatter('%Y-%m-%d')
fig = plt.figure(figsize=(15,4))
ax = fig.add_subplot(111)
ax.xaxis.set_major_formatter(xfmt)
lst_predictions = list(predictions2)
len_predictions = len(lst_predictions)
plt.plot(lst_index, list(test_y2), label = 'actual')
plt.ylim(ymin=0) 
plt.ylim(ymax=140)  
plt.xlim([lst_index[0], lst_index[-1]])
plt.plot(lst_index, lst_predictions, label='pred')

plt.legend(loc="upper left")
plt.grid(True)

Upvotes: 0

Views: 230

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339250

You can use a DayLocator to control the location of the ticks.

xloc = mdates.DayLocator(interval=50)
ax.xaxis.set_major_locator(xloc)

Usually you would use it in cases where you want to mark the 1st and 15th of each month or so. Since 50 days is more than a month, the location cannot be determined in terms of a month. You may still use the interval argument to space the ticks 50 days appart. However the starting point will be rather arbitrary.

Complete code:

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

start_date = datetime.date(2016, 04, 01)
end_date   = datetime.date(2017, 07, 01)
date_list = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]

values = np.cumsum(np.random.rand(len(date_list))-.5)+20

fig, ax = plt.subplots(figsize=(15,4))

ax.plot(date_list, values, label = 'actual')

xloc = mdates.DayLocator(interval=50)
ax.xaxis.set_major_locator(xloc)

xfmt = mdates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_formatter(xfmt)

plt.legend(loc="upper left")
plt.grid(True)

plt.show()

enter image description here

Upvotes: 2

Related Questions