问题
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")
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")
回答1:
If you don't want to call bar
twice and only want the second y axis to provide a conversion, then simply don't call bar at all the second time. You can still create and adjust the second y axis without actually plotting anything on it.
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.set_ylabel('Consumption in EUR')
ax.set_ylim(ymax=y2max)
ax2.set_ylim(ymax=4.2*y2max)
来源:https://stackoverflow.com/questions/36104251/matplotlib-pyplot-how-to-set-up-a-second-y-axis-for-an-existing-plot