Matplotlib.pyplot:如何为现有绘图设置第二个y轴 [英] Matplotlib.pyplot: How to set up a second y-axis for an existing plot

查看:114
本文介绍了Matplotlib.pyplot:如何为现有绘图设置第二个y轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两组线性相关的值.因此,我只需要一个带有第二个y轴且正确比例的图形.

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")

非常感谢!:-)

编辑:

我可能还不清楚.我想制作一个单个图.类似于以下内容.但是,有没有比两次调用bar函数并用 alpha = 0 隐藏它更好的方法了?

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")

推荐答案

如果您不想调用两次 bar ,而只希望第二个y轴提供转换,则只需t第二次打电话给酒吧.您仍然可以创建和调整第二个y轴,而无需在其上实际绘制任何内容.

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)

这篇关于Matplotlib.pyplot:如何为现有绘图设置第二个y轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆