Todd Chou
Todd Chou

Reputation: 37

Changing the formatting of a datetime axis in matplotlib (bar chart)

I have created following bar chart:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

ts = pd.Series(np.random.randn(1000),index=pd.date_range('1/2/2000', periods=1000))
df = pd.DataFrame(np.random.randn(1000,4), index = ts.index, columns = list('ABCD'))
df = df.cumsum()
df.iloc[0:5].plot.bar()

The result looks like this: enter image description here

How could I change the format of x axis to 1) Y-M-D without hour and minutes and 2) rotate the xaxis label by 50 degrees?

I have looked into this and managed to create a line chart: Changing the formatting of a datetime axis in matplotlib

import matplotlib.dates as mdates

fig, ax = plt.subplots()
ax.plot(df.index[0:5], df.values[0:5])
ax.set_xticks(df.index[0:5])
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m-%d"))
_=plt.xticks(rotation=50)

enter image description here

In order to get a bar chart with the desired xaxis label I have tried following but got "ValueError: shape mismatch: objects cannot be broadcast to a single shape":

fig, ax = plt.subplots()
ax.bar(df.index[0:5], df.values[0:5])
ax.set_xticks(df.index[0:5])
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m-%d"))
_=plt.xticks(rotation=50) 

Could anyone please tell me how I could get to the bar chart?

Is there a way to use only pyplot without axes?

Thank you.

Upvotes: 0

Views: 1072

Answers (1)

Arne
Arne

Reputation: 10545

You can transform your time index to the appropriate format with strftime and then do the plot, passing rot=1 for the label rotation:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

ts = pd.Series(np.random.randn(1000),index=pd.date_range('1/2/2000', periods=1000))
df = pd.DataFrame(np.random.randn(1000,4), index = ts.index, columns = list('ABCD'))
df = df.cumsum()

df.index = df.index.strftime('%Y-%m-%d')
df.iloc[0:5].plot.bar(rot=1)

enter image description here

Upvotes: 2

Related Questions