简体   繁体   English

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

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

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. 因此,我只需要一个带有第二个y轴且尺寸合适的图形。

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 ? 但是,有没有比两次调用bar函数并用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")

示例代码2

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. 如果您不想两次调用bar而只希望第二个y轴提供转换,那么根本就不要第二次调用bar。 You can still create and adjust the second y axis without actually plotting anything on it. 您仍然可以创建和调整第二个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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM