Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stacked area plot and dates in matplotlib

Here is my code:

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
dates =  ['2014-12-15','2015-11-07','2016-01-10']
x = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates]
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.stackplot(x,[1,2,3],[7,8,3])
plt.gcf().autofmt_xdate()
plt.show()

It produces the following plot:

ugly plot

How do I fix it to have only 3 dates? I followed the following example: SO example

like image 680
user1700890 Avatar asked Apr 24 '26 19:04

user1700890


1 Answers

You just need to set xticks with the following command:

plt.xticks(x)

Just add this line before you display the figure. DayLocator displays every single day by default. In your case, you have too many days in between to display. You can just remove line 7 which sets the Daylocator and replace it with the above line which sets the ticks to be your dates. This is the result: enter image description here

like image 106
Longwen Ou Avatar answered Apr 26 '26 07:04

Longwen Ou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!