Matplotlib.pyplot: How to set up a second y-axis for an existing plot

Viewed 6592

I have two sets of values that are linearly dependent. Therefore I just need a single graph with a second y-axis in the right scale.

What is the most elegant way to do this?

Making just two bar-plots gives me an overlap:

import numpy as np
import matplotlib.pyplot as plt 

x = np.arange(4)
y2 = np.array([23, 32, 24, 28])
y1 = 4.2 * y2

fig = plt.figure(1, figsize=(6,6))

ax = fig.add_subplot(111)
ax.bar(x, y2) 
ax.set_ylabel('Consumption in $m^3$')
ax2 = ax.twinx()
ax2.bar(x, y1, alpha=0.5) 
ax2.set_ylabel('Consumption in EUR')

plt.savefig('watercomsumption.png', format='png', bbox_inches="tight")

example-plot

Thanks alot! :-)


EDIT:

I might have been unclear. I would like to make a single graph. Something like the following. But is there a more elegant way than calling the bar-function twice and hiding it with alpha=0?

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(4)
y2 = np.array([23, 32, 24, 28])
y1 = 4.2 * y2

y2max = np.max(y2) * 1.1

fig = plt.figure(1, figsize=(6,6))

ax = fig.add_subplot(111)
ax.bar(x, y2)
ax.set_ylabel('Consumption in $m^3$')
ax2 = ax.twinx()

ax2.bar(x, y1, alpha=0)
ax2.set_ylabel('Consumption in EUR')

ax.set_ylim(ymax=y2max)
ax2.set_ylim(ymax=4.2*y2max)

plt.savefig('watercomsumption.png', format='png', bbox_inches="tight")

example-code2

1 Answers
Related