I want to plot temperature data as a line, with rainfall data as a bar. I can do this easily in Excel but I'd prefer a fancy python graph to show it in a nicer way.
Some sample code to illustrate the problem:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
dates = pd.date_range('20070101',periods=365)
df = pd.DataFrame(data=np.random.randint(0,50,(365,4)), columns =list('ABCD'))
df['date'] = dates
df = df[['date','A', 'B', 'C', 'D']]
df.set_index(['date'],inplace=True) #set date as the index so it will plot as x axis
This creates a dataframe with four columns (imagine A and B are temp and C and D are rainfall).
I want to plot rainfall as bars, and temp as a line, but when I try to do this:
ax = df.plot(y="A", kind="bar")
df.plot(y="B", kind = "line", ax = ax)
The lines plot but not the bars.
This is a much simpler version of what I'm trying to do but I think it illustrates the problem.
EDIT:
The following code works:
fig, ax= plt.subplots()
ax.plot_date(df.index, df.iloc[:,2], '-')
for i in range(3):
diff = df.index[1]-df.index[0]
spacing = diff/(1.3*len(df.columns))
ax.bar(df.index+(-5+i)*spacing, df.iloc[:,i],
width=spacing/diff, label=df.columns[i])
plt.legend()
plt.gcf().autofmt_xdate()
plt.show()
Would really appreciate a less complex answer as this seems quite verbose but it seems to work!