I have a pandas dataframe with random numbers where the index is of type dtype='datetime64[ns]
. You'll find reproducible code at the end of the question.
When I plot this using ax.dfplot()
, I get a beautifully formatted x-axis like this:
I would like to make a bar chart out of this instead, but when I use ax = df.plot(kind = 'bar')
, the x axis gets messed up:
How can i change this?
Thank you for any suggestions!
Reproducible code for input data frame and the two first charts:
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
# Dataframe with 1 or zero
np.random.seed(123)
rows = 10
df = pd.DataFrame(np.random.randint(90,110,size=(rows, 2)), columns=list('AB'))
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
print(df.head(10))
#print(df)
# Option 1
# -Time series
# -kind is undefined
title = 'time series'
ax = df.plot(title = title, fontsize = 10)
#ax.legend().set_visible(legend)
# Option 2
# -Bar chart
# -kind is defined as bar
title = 'Bar'
ax = df.plot(title = title, fontsize = 10, kind = 'bar')
Here is what I've tried so far:
Here is a somewhat similar question, but I'm having problems with the reproducible snippet provided there. Perhaps a version problem since it is a few years old?
I have also been able to at least improve the format using the suggestions here:
title = 'Bar'
ax = df.plot(title = title, fontsize = 10, kind = 'bar')
xtl=[item.get_text()[:10] for item in ax.get_xticklabels()]
_=ax.set_xticklabels(xtl)
I had high hopes for the suggestions here as well since it seemed I would at least be able to display months only du to the mdates.DateFormatter('%d')
part (using m instead). But I'm having problems showing the results:
title = 'Bar'
ax = df.plot(title = title, fontsize = 10, kind = 'bar')
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
I'm only getting this: