【问题标题】:Plot a curve on top of 2 subplots simultaneously同时在 2 个子图上绘制曲线
【发布时间】:2021-11-28 18:31:47
【问题描述】:

编辑:我的问题已关闭,因为有人认为另一个问题正在回应它(但它没有:Matplotlib different size subplots)。为了澄清我想要的东西: 我想复制类似这张照片所做的事情:将第三个数据集绘制在 2 个子图之上,其 y 轴显示在右侧。

我有 3 个数据集跨越相同的时间间隔(速度、位置、降水)。我想在 2 个水平子图中绘制速度和位置,以及跨越 2 个子图的降水量。 例如在下面的代码中,我不想让twinx() 仅在第一个子图上,而是让它与两个子图重叠(即,在右侧有一个 y 轴,右下角为 0第二个子图,第一个子图右上角的 20 个)。 我能做到吗?

import matplotlib.pyplot as plt
import numpy as np



fig, ax = plt.subplots(2,1,figsize=(20,15), dpi = 600)
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

ax[0].plot(x,y, label = 'speed')
plt.legend()

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

ax[1].plot(x,y, label = 'position')
plt.legend()


#plot 3:

x = np.array([0, 1, 2, 3])
y = np.array([10, 0, 4, 20])
ax2=ax[0].twinx()
ax2.plot(x,y, label = 'precipitation')

plt.legend(loc='upper right')
plt.show()

【问题讨论】:

    标签: python matplotlib plot axis subplot


    【解决方案1】:

    我发现的最佳方式不是很优雅,但它确实有效:

    # Prepare 2 subplots
    fig, ax = plt.subplots(2,1,figsize=(20,15), dpi = 600)
    #plot 1:
    
    # Dummy values for plotting
    x = np.array([0, 1, 2, 3])
    y = np.array([3, 8, 1, 10])
    
    ax[0].plot(x,y, label = 'speed')
    
    # Prints the legend
    plt.legend()
    
    #plot 2:
    x = np.array([0, 1, 2, 3])
    y = np.array([3, 8, 1, 10])
    
    ax[1].plot(x,y, label = 'position')
    plt.legend()
    
    
    #plot 3:
    
    x = np.array([0, 1, 2, 3])
    y = np.array([10, 0, 4, 20])
    
    # Add manually a 3rd subplot that stands on top of the 2 others
    ax2 = fig.add_subplot(111, label="new subplot", facecolor="none")
    
    # Move the y-axis to the right otherwise it will overlap with the ones on the left 
    ax2.yaxis.set_label_position("right")
    
    # "Erase" every tick and label of this 3rd plot
    ax2.tick_params(left=False, right=True, labelleft=False, labelright=True,
                    bottom=False, labelbottom=False)
    
    # This line merges the x axes of the 1st and 3rd plot, and indicates
    # that the y-axis of the 3rd plot will be drawn on the entirety of the 
    # figure instead of just 1 subplot (because fig.add_subplot(111) makes it spread on the entirety of the figure) 
    ax[0].get_shared_x_axes().join(ax[0],ax2)
    ax2.plot(x,y, label = 'precipitation')
    
    # Prints the legend in the upper right corner
    plt.legend(loc='upper right')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多