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

3

我有两组线性相关的值。因此,我只需要一个带有第二个 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")

例子-绘图

非常感谢! :-)


编辑:

我可能没有表达清楚。我想制作一个单独的图表,就像下面这样。但是有没有更优雅的方法来调用两次柱形图函数并使用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个回答

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)

enter image description here


非常感谢您的努力,但这不是我要找的。也许我的问题表述不清楚,但我正在寻找一种方法,而不必调用bar函数两次。我在上面添加了另一个示例!再次感谢! - Suuuehgi
@smoneck 在第二部分中进行了更新。只需不调用bar函数,并且仅修改ylims参数即可。 - Suever
改变问题的质量是非常不幸的,但无论如何还是非常感谢提示 - 就是这样!总是最明显的你没有注意到...或者在冰箱里面,在中间。 :-) - Suuuehgi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接