来自多个excel的子图

  • 本文关键字:子图 excel python
  • 更新时间 :
  • 英文 :


我正在处理20个优秀的。对于每个excel,我做相同的子集和绘图。我现在可以得到20个独立的数字使用for循环。但我怎么能把这些数字放在一个子图(5*4)?查看一些帖子,但无法得到答案。

for files in allfiles:
    #if re.search(r".*.xlsx", files):
        df = pd.read_excel("D:Brown researchTask2 site selectionAll_excel{0}".format(files))  
        newdf = df[(df.slope != 0) & (df.AI >= 0.8) & (df.reach_len > 5000)]
        
        Q1=df['slope'].quantile(0.25)
        Q3=df['slope'].quantile(0.75)
        IQR=Q3-Q1
 
        Upper_Whisker = Q3+3*IQR
        newdf = newdf[newdf['slope']<Upper_Whisker]
        
        x = newdf['slope'] 
        y = newdf['AI']
        
        nbins = 20
        plt.figure()
        plt.hist2d(x,y,nbins,cmap=plt.cm.coolwarm, cmin=1)
        plt.colorbar()
        plt.title(files.split('_')[0],x=0.5,y=0.9)

提前创建您的图形和轴,并使用matplotlib的面向对象接口:

from pathlib import Path
from matplotlib import pyplot
import pandas
basedir = Path(r"D:Brown researchTask2 site selectionAll_excel")
fig, axes = pyplot.subplots(5, 4, figsize=(10, 10))
for xlfile, ax in zip(basedir.glob("*.xlsx"), axes.flat):
    df = pandas.read_excel(xlfile) 
    Q1=df['slope'].quantile(0.25)
    Q3=df['slope'].quantile(0.75)
    IQR=Q3-Q1
    Upper_Whisker = Q3+3*IQR
    
    newdf = df.loc[lambda df: 
        (df["slope"] != 0) &
        (df["slope"] < Upper_Whisker) &
        (df["AI"] >= 0.8) &
        (df["reach_len"] > 5000) 
    ]
    x = newdf['slope'] 
    y = newdf['AI']
    nbins = 20
    hist = ax.hist2d(x,y,nbins,cmap=plt.cm.coolwarm, cmin=1)
    fig.colorbar(hist)
    ax.set_title(xlfile.stem.split('_')[0], x=0.5, y=0.9)

假设目录中有20个文件。

更好的是,我会将所有内容连接到单个数据帧中,并使用seaborn动态构建情节:

from pathlib import Path
from matplotlib import pyplot
import pandas
import seaborn
def get_upper_whisker(df, column):
    Q1 = df[column].quantile(0.25)
    Q3 = df[column].quantile(0.75)
    IQR = Q3 - Q1
    return Q3 + (3 * IQR)
basedir = Path(r"D:Brown researchTask2 site selectionAll_excel")
data = pandas.concat([
    pandas.read_excel(xlfile).assign(file=xlfile.stem)
    for xlfile in basefir.glob("*.xlsx")
])
fig = (
    data.groupby("file")
        .apply(lambda g: 
            g.loc[g["slope"] < get_upper_whisker(g, "slope")]
        )
        .loc[lambda df:
            (df["slope"] != 0) &
            (df["AI"] >= 0.8) &
            (df["reach_len"] > 5000)     
        ]
        .pipe(seaborn.FacetGrid, col="file", col_wrap=4)
)
fig.map(pyplot.hist2d, "slope", "AI", bins=20, cmap=pyplot.cm.coolwarm, cmin=1)

感谢@Paul H.提供的两个解决方案,对于解决方案1,只需要稍微修改一下,例如:"fig.colorbar(hist[3],ax=ax)"[3]是"图像">

最新更新