1

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!

Pad
  • 841
  • 2
  • 17
  • 45
  • The x-axes are incompatible (try plotting the two separately). – IanS Sep 06 '17 at 14:56
  • Related: https://stackoverflow.com/questions/30133280/pandas-bar-plot-changes-date-format – IanS Sep 06 '17 at 14:57
  • I've edited the question to respond to your suggestion, created a new x axis based on date but the result is the same – Pad Sep 06 '17 at 15:10
  • Because your index is datetime, you run into the same problem really. You could convert the index to a string representation (and only show a tick label per month). – IanS Sep 06 '17 at 15:17
  • 2
    Did you read [this question](https://stackoverflow.com/questions/42813890/python-making-combined-bar-and-line-plot-with-secondary-y-axis)? In how far does it not help? – ImportanceOfBeingErnest Sep 06 '17 at 15:21
  • I had not read that question, I will try that with my data as it works for the example data – Pad Sep 06 '17 at 15:33

1 Answers1

2

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

IanS
  • 15,771
  • 9
  • 60
  • 84