【问题标题】:Matplotlib: create two subplots in line with two y axes eachMatplotlib:创建两个子图,每个子图有两个 y 轴
【发布时间】:2017-06-29 21:27:52
【问题描述】:

This matplotlib tutorial 展示了如何创建具有两个 y 轴(两个不同比例)的绘图:

import numpy as np
import matplotlib.pyplot as plt


def two_scales(ax1, time, data1, data2, c1, c2):

    ax2 = ax1.twinx()

    ax1.plot(time, data1, color=c1)
    ax1.set_xlabel('time (s)')
    ax1.set_ylabel('exp')

    ax2.plot(time, data2, color=c2)
    ax2.set_ylabel('sin')
    return ax1, ax2


# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
s2 = np.sin(2 * np.pi * t)

# Create axes
fig, ax = plt.subplots()
ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b')


# Change color of each axis
def color_y_axis(ax, color):
    """Color your axes."""
    for t in ax.get_yticklabels():
        t.set_color(color)
    return None

color_y_axis(ax1, 'r')
color_y_axis(ax2, 'b')
plt.show()

结果是这样的:

我的问题:您将如何修改代码以创建两个像这样的子图,仅水平对齐? 我会做类似的事情

fig, ax = plt.subplots(1,2,figsize=(15, 8))
plt.subplot(121)
###plot something here
plt.subplot(122)
###plot something here

但是您如何确保调用以创建轴的 fig, ax = plt.subplots() 不会与调用以创建水平对齐的画布的 fig, ax = plt.subplots(1,2,figsize=(15, 8)) 发生冲突?

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    您将创建两个子图fig, (ax1, ax2) = plt.subplots(1,2) 并将two_scales 应用于每个子图。

    import numpy as np
    import matplotlib.pyplot as plt
    
    def two_scales(ax1, time, data1, data2, c1, c2):
        ax2 = ax1.twinx()
        ax1.plot(time, data1, color=c1)
        ax1.set_xlabel('time (s)')
        ax1.set_ylabel('exp')
        ax2.plot(time, data2, color=c2)
        ax2.set_ylabel('sin')
        return ax1, ax2
    
    # Create some mock data
    t = np.arange(0.01, 10.0, 0.01)
    s1 = np.exp(t)
    s2 = np.sin(2 * np.pi * t)
    
    # Create axes
    fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,4))
    ax1, ax1a = two_scales(ax1, t, s1, s2, 'r', 'b')
    ax2, ax2a = two_scales(ax2, t, s1, s2, 'gold', 'limegreen')
    
    # Change color of each axis
    def color_y_axis(ax, color):
        """Color your axes."""
        for t in ax.get_yticklabels():
            t.set_color(color)
    
    color_y_axis(ax1, 'r')
    color_y_axis(ax1a, 'b')
    color_y_axis(ax2, 'gold')
    color_y_axis(ax2a, 'limegreen')
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • 这完全是你的选择。您拥有所有四个轴的轴手柄。所以你可以调用ax.set_title("mytitle"),其中 ax 是轴之一,在函数内部或外部。如果在内部,该函数需要将标题字符串作为参数。
    【解决方案2】:

    这是你想要的吗?

    [...]
    # Create some mock data
    t = np.arange(0.01, 10.0, 0.01)
    s1 = np.exp(t)
    s2 = np.sin(2 * np.pi * t)
    
    # Create axes
    ax = plt.subplot(2,2,1)
    ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b')
    
    ax = plt.subplot(2,2,2)
    ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b')
    [...]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多