Matplotlib pyplot - tick control and display date

Mine has matplotlib pyplot

too many xticks

- it shows every year and month over a 15 year period, for example. "2001-01", but I want the x-axis to show the year (eg 2001).

The output will be a line graph where the x-axis shows dates and the y-axis shows the sale and rental prices.

# Defining the variables
ts1 = prices['Month'] # eg. "2001-01" and so on
ts2 = prices['Sale'] 
ts3 = prices['Rent'] 

# Reading '2001-01' as year and month
ts1 = [dt.datetime.strptime(d,'%Y-%m').date() for d in ts1]

plt.figure(figsize=(13, 9))
# Below is where it goes wrong. I don't know how to set xticks to show each year. 
plt.xticks(ts1, rotation='vertical')
plt.xlabel('Year')
plt.ylabel('Price')
plt.plot(ts1, ts2, 'r-', ts1, ts3, 'b.-')
plt.gcf().autofmt_xdate()
plt.show()

      

+3


source to share


2 answers


You can do this with plt.xticks

.

As an example, here I have set the xticks frequency to display every three indices. In your case, you probably want to do this every twelve indices.



import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.random.randn(10)

plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 3))
plt.show()

      

In your case, since you are using dates, you can replace the second argument with the last line above with something like ts1[0::12]

that will select every 12th item from, ts1

or np.arange(0, len(dates), 12)

that will select every 12th index corresponding to the ticks you want show.

+1


source


Try to remove the function call entirely plt.xticks

. matplotlib will use a function AutoDateLocator

to find the optimal tick locations.

Alternatively, if the default is multiple months, which you don't want, you can use matplotlib.dates.YearLocator

that will force the ticks to be years only.

You can set the locator as shown below in a short example:



import matplotlib.pyplot as plt
import matplotlib.dates as mdate
import numpy as np
import datetime as dt

x = [dt.datetime.utcnow() + dt.timedelta(days=i) for i in range(1000)]
y = range(len(x))

plt.plot(x, y)

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

plt.gcf().autofmt_xdate()

plt.show()

      

enter image description here

+2


source







All Articles