Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating Dates in x-axis Pandas Matplotlib

I have a pretty simple set of data as displayed below. I am looking for a way to plot this stacked bar chart and format the x-axis (dates) so it starts at 1996-31-12 and ends at 2016-31-12 on increments of 365 days. The code I have written is plotting every single date and therefore the x-axis is very bunched up and not readable.

Datafame:

Date             A             B  
1996-31-12       10            3
1997-31-03       5             6
1997-31-07       7             5
1997-30-11       3             12
1997-31-12       4             10
1998-31-03       5             8
.
.
.
2016-31-12       3             9
like image 879
spacedinosaur10 Avatar asked Mar 25 '26 17:03

spacedinosaur10


1 Answers

This is a similar question: Pandas timeseries plot setting x-axis major and minor ticks and labels

You can manage this using matplotlib itself instead of pandas.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# if your dates are strings you need this step
df.Date = pd.to_datetime(df.Date)

fig,ax = plt.subplots()
ax.plot_date(df.Date,df.A)
ax.plot_date(df.Date,df.B)
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b\n%Y'))
plt.show()
like image 99
mechanical_meat Avatar answered Mar 28 '26 07:03

mechanical_meat



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!