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 pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinedates = pd.date_range('20070101',periods=365)df = pd.DataFrame(data=np.random.randint(0,50,(365,4)), columns =list('ABCD'))df['date'] = datesdf = 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!
Best Answer
A simple way would be to use the x_compat
property:
ax = df.plot(x=index, y="A", x_compat=True) # plot lines firstdf.plot(x=index, y="B", kind="bar", ax=ax)
You can then adjust the tick frequency.
Hat-tip: https://stackoverflow.com/a/39907390/5276797