1

I am trying to change my x-axis ticks from day to month in my grouped bar plot. I tried solutions from here and here and here but none of them worked. My code to display the plot with daily ticks which works is the following:

ax = data.groupby(['pos', data['date'].dt.strftime('')])['date'].count().unstack(0).plot.bar(title = 'TITLE', figsize=(14,8))
_ = ax.set_xlabel('day')
_ = ax.set_ylabel('count')
mylabels = ['R', 'L']
_ = ax.legend(labels=mylabels)
plt.show()

daily plot I tried the following which didn't work (but also didn't throw an error):

data['date_for_index'] = data['date']
data = data.set_index('date_for_index')
ax = data.groupby(['pos', data['date'].dt.strftime('')])['date'].count().unstack(0).plot.bar(title = 'TITLE', figsize=(14,8))
_ = ax.set_xlabel('day')
_ = ax.set_ylabel('count')
mylabels = ['R', 'L']
ax.set_xticks(data.index)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_ = plt.xticks(rotation=90) 
mylabels = ['R', 'L']
_ = ax.legend(labels=mylabels)
plt.show()
LN_P
  • 1,448
  • 4
  • 21
  • 37
  • It's not possible to use `matplotlib.dates` tickers with pandas bar plots, because they use entirely different units. You can (a) create a matplotlib bar plot and use the matplotlib.dates tickers, (b) Set the xticks manually for the pandas bar plot. – ImportanceOfBeingErnest Jul 02 '19 at 13:46

1 Answers1

1

How I ended up doing it:

grouped_data = data \
.groupby(['pos', data['date'].dt.strftime('')])['date'] \
.count() \
.unstack(0) \
.reset_index()
grouped_data.columns = ['date', 'r_count', 'l_count']
grouped_data['date'] = pd.to_datetime(grouped_data['date'])

fig, ax = plt.subplots(figsize=(14, 8))
ax.bar(grouped_data['date'], grouped_data['r_count'])
ax.bar(grouped_data['date'], grouped_data['l_count'])
ax.xaxis_date()
ax.set_xlabel('date')
ax.set_ylabel('count')
mylabels = ['r', 'l']
ax.legend(labels=mylabels)
plt.show()

plot

LN_P
  • 1,448
  • 4
  • 21
  • 37