从 python 中的多个 excel 工作表使用 for 循环创建子图

Creating subplot using for loop from multiple excel sheets in python

我正在尝试使用 for 循环创建子图,其中数据基于多个 excelsheet。你可以看到下面的脚本。

#import libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

#import the excel file
path ='F:\Backup\JN\TOR\TOR well py.xlsx'
data= pd.ExcelFile(path)

#some intro before getting into the for in loop
sheets = data.sheet_names
well = ''
totalsheets = len(sheets)
print(sheets)
print(totalsheets)

for n in range(totalsheets):
    fig, axs=plt.subplots(1, totalsheets, figsize=(20,25))
    for i in sheets:
        well=pd.read_excel(data, sheet_name=i)
        axs[n].set_xlabel('Temperature ($^o$C), Pressure (bar)')
        axs[n].set_ylabel('Elevation (masl)')
        axs[n].set_title(('Well-'+str(i)+ '\n' )+ (str(well['ket'][0])))
        axs[n].plot(well['T'], well['mdpl pt'], marker='o', color='blue', label='Temperature')
        axs[n].plot(well['P'], well['mdpl pt'], marker='o', color='crimson', label='Pressure')

脚本生成了 11 个子图(1 行 11 列),而不是得到一个 1 行 11 列的子图,其中每个子图代表每个数据 sheets。子图中描述的数据仅来自最后一个 sheets 'P1',这些数据从第一列开始按顺序绘制到每个子图中,然后是第二、第三、第四等等(见下图,我只显示了 11 个数字中的 3 个)。

看到结果后,我想我的for循环脚本做错了。请帮忙,非常感谢。

['E1', 'E2', 'E3', 'E4', 'G1', 'C1', 'C2', 'A1'、'A2'、'A3'、'P1']

11

将图移到for循环之外后,我成功创建了一个包含11个子图的图。但是所有 11 个子图只显示来自一个 sheet(仅 P1)的数据,而不是 excel 中的 11 个 sheets 来填充每个子图 ['E1','E2', 'E3', 'E4', 'G1', 'C1', 'C2', 'A1', 'A2', 'A3', 'P1'].我是否遗漏了 for 循环脚本中的某些内容? (见下方截图)

请检查代码段。

您已经在 for 循环中创建了 fig, axs=plt.subplots(1, totalsheets, figsize=(20,25))。在这里,您的 totalsheets=11 因此您收到了 11 行中的 11 个地块。

只需将您的 fig 放在 for 循环之外,您的问题就会得到解决。

import numpy as np
import matplotlib.pyplot as plt

totalsheets=11
fig, axs = plt.subplots(nrows=1, ncols=totalsheets, figsize=(12,5))
x = [1, 2, 3]
y = [4, 5, 6]
sheets=["a","b","c","d","e","f","g","h","i","j","k"]
for n in range(totalsheets):
    for i in sheets:
        axs[n].plot(x, y)
        axs[n].set_xlabel('TP')
        axs[n].set_ylabel('EL')
        axs[n].set_title('Well-'+str(i)+ '\n' )
fig.tight_layout()
plt.show()

编辑: 根据您的评论,这将从不同的工作表中获取数据,可能数据列名称应该相同

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data= pd.ExcelFile('datas.xlsx')
sheets=data.sheet_names
fig, axs = plt.subplots(nrows=1, ncols=len(sheets), figsize=(7,5))
for n in range(len(sheets)):
    well=pd.read_excel('datas.xlsx', sheet_name=n)
    axs[n].plot(well['a'], well['b'])
    axs[n].set_xlabel('TP')
    axs[n].set_ylabel('EL')
    axs[n].set_title('Well-'+str(sheets[n])+ '\n' )   
fig.tight_layout()
plt.show()