【问题标题】:Stacking multiple plots on a 2Y axis在 2Y 轴上堆叠多个图
【发布时间】:2019-09-01 22:10:17
【问题描述】:

我正在尝试在 2Y 图中绘制多个图。

我有以下代码:

  • 有一个文件列表来获取一些数据;
  • 获取要在 y 轴 1 和 y 轴 2 上绘制的数据的 x 和 y 分量;
  • 绘制数据。

当循环迭代时,它会绘制在不同的图形上。我想把所有的地块都放在同一个图中。 谁能帮我解决这个问题?

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
file=[list of paths]

for i in files:

 # Loads Data from an excel file
    data = pd.read_excel(files[i],sheet_name='Results',dtype=float)

 # Gets x and y data from the loaded files
    x=data.iloc[:,-3]
    y1=data.iloc[:,-2]
    y12=data.iloc[:,-1]
    y2=data.iloc[:,3]

    fig1=plt.figure()
    ax1 = fig1.add_subplot(111)    
    ax1.set_xlabel=('x')
    ax1.set_ylabel=('y')

    ax1.plot(x,y1)
    ax1.semilogy(x,y12)

    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
    ax2.plot(x,y2)

    fig1.tight_layout()  

    plt.show()








【问题讨论】:

    标签: matplotlib plot spyder


    【解决方案1】:

    您应该在循环外实例化图形,然后在迭代时添加子图。这样,您将拥有一个图形和其中的所有图。

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    files=[list of paths]
    
    fig1=plt.figure()
    
    for i in files:
    
     # Loads Data from an excel file
        data = pd.read_excel(files[i],sheet_name='Results',dtype=float)
    
     # Gets x and y data from the loaded files
        x=data.iloc[:,-3]
        y1=data.iloc[:,-2]
        y12=data.iloc[:,-1]
        y2=data.iloc[:,3]
    
        ax1 = fig1.add_subplot(111)    
        ax1.set_xlabel=('x')
        ax1.set_ylabel=('y')
    
        ax1.plot(x,y1)
        ax1.semilogy(x,y12)
    
        ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
        ax2.plot(x,y2)
    
        fig1.tight_layout()  
    
        plt.show()
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2012-11-30
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多