Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib pyplot - tick control and showing date

My matplotlib pyplot has too many xticks - it is currently showing each year and month for a 15-year period, e.g. "2001-01", but I only want the x-axis to show the year (e.g. 2001).

The output will be a line graph where x-axis shows dates and the y-axis shows the sale and rent 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()
like image 202
Coloane Avatar asked Aug 13 '14 06:08

Coloane


People also ask

How do I change the format of a tick in Matplotlib?

Tick formatters can be set in one of two ways, either by passing a str or function to set_major_formatter or set_minor_formatter , or by creating an instance of one of the various Formatter classes and providing that to set_major_formatter or set_minor_formatter .

Is PLT show () blocking?

show() and plt. draw() are unnecessary and / or blocking in one way or the other.

Can Matplotlib plot dates?

MatPlotLib with PythonUsing Pandas, we can create a dataframe and can set the index for datetime. Using gcf(). autofmt_xdate(), we will adjust the date on the X-axis.

Is PLT show () necessary?

Using plt. show() in Matplotlib mode is not required.


2 Answers

Try removing the plt.xticks function call altogether. matplotlib will then use the default AutoDateLocator function to find the optimum tick locations.

Alternatively if the default includes some months which you don't want then you can use matplotlib.dates.YearLocator which will force the ticks to be years only.

You can set the locator as shown below in a quick 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

like image 148
Ffisegydd Avatar answered Oct 07 '22 15:10

Ffisegydd


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 would probably want to do so 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 argument of the second to last line above with something like ts1[0::12], which will select every 12th element from ts1 or np.arange(0, len(dates), 12) which will select every 12th index corresponding to the ticks you want to show.

like image 43
Pythontology Avatar answered Oct 07 '22 16:10

Pythontology