【问题标题】:Matplotlib.pyplot: How to set up a second y-axis for an existing plotMatplotlib.pyplot:如何为现有绘图设置第二个 y 轴
【发布时间】:2016-07-06 09:08:08
【问题描述】:

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

非常感谢! :-)


编辑:

我可能不清楚。我想制作一个 single 图表。 类似于以下内容。但是有没有比两次调用 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")

【问题讨论】:

    标签: python matplotlib bar-chart


    【解决方案1】:

    如果您不想调用 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)
    

    【讨论】:

    • 非常感谢您的努力,但这不是我想要的。我的问题可能不清楚,但我正在寻找一种无需两次调用 bar 函数的方法。我在上面添加了另一个示例!再次,非常感谢!
    • @smoneck 在第二部分更新。根本不要打电话给bar,只改变ylims。
    • 从质量上改变问题是非常不幸的,但无论如何非常感谢您的提示 - 做到了!它总是最明显的你没有注意到......或者中间前面的冰箱里有什么。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2023-04-07
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    相关资源
    最近更新 更多