Matplotlib.pyplot:如何为现有绘图设置第二个y轴

Suu*_*hgi 1 python matplotlib bar-chart

我有两组线性相关的值.因此,我只需要一个右图中具有第二个y轴的单个图形.

这样做最优雅的方法是什么?

只制作两个条形图给我一个重叠:

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")
Run Code Online (Sandbox Code Playgroud)

例如,情节

非常感谢!:-)


编辑:

我可能一直不清楚.我想提出一个单一的图形.像下面这样的东西.但有没有比调用条形函数两次并隐藏它更优雅的方式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")
Run Code Online (Sandbox Code Playgroud)

例如,码2

Sue*_*ver 5

如果您不想调用bar两次并且只希望第二个y轴提供转换,那么第二次只需要不调用bar.您仍然可以创建和调整第二个y轴,而无需在其上实际绘制任何内容.

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述