Pad
Pad

Reputation: 911

Plotting lines and bars from pandas dataframe on same graph using matplotlib

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!

Upvotes: 1

Views: 2986

Answers (1)

IanS
IanS

Reputation: 16261

A simple way would be to use the x_compat property:

ax = df.plot(x=index, y="A", x_compat=True)  # plot lines first
df.plot(x=index, y="B", kind="bar", ax=ax)

You can then adjust the tick frequency.

Hat-tip: https://stackoverflow.com/a/39907390/5276797

Upvotes: 2

Related Questions