首页 > 解决方案 > 如何在 plotly 中创建一个包含 6 行子图的图?

问题描述

我有 6 个不同的数据框,我想制作 1 个图形,显示 6 个图形,x 轴为年份,y 轴为每 100k 的事件案例。我一直在使用以下代码来创建我想要的单个图形,但现在我被困在如何将它们全部放入一个图形中。

px.line(gyeEUR, x="year", y="incident cases per 100k", color="country", title="Incident Cases per 100k in Europe")

我只是想使用 6 个不同的数据帧(即 gyeEUR、gyeEMR ....)将此图 6 次。解决此问题的最佳方法是什么?

标签: pythonplotly

解决方案


您可能会考虑读取所有 6 个数据框,向它们添加一列 df_i["fn"]= "filename" ,最后将它们连接到更大的数据框df并使用

px.line(df,
        x="year",
        y="incident cases per 100k",
        color="country",
        title="Incident Cases per 100k in Europe",
        facet_row="fn")

更新:完整示例

生成数据

在这里,我们简单地读取内置gapminder的数据,plotly.express并将其拆分为大陆的几个文件。鉴于大陆在文件名中,我们将该列放在每个组中

import os
import plotly.express as px
os.makedirs("data", exist_ok=True)

df = px.data.gapminder()

df.groupby("continent")\
  .apply(lambda x: 
         x.drop("continent", axis=1)\
          .to_csv("data/{}.csv".format(x.name),
                  index=False))

读取数据并连接

# list all csv in data/
files = os.listdir("data/")
files = list(filter(lambda f: f.endswith('.csv'), files))

# read, add continent and concat

out = []
for file in files:
    df = pd.read_csv(f"data/{file}")
    df["continent"] = file[:-4]
    out.append(df)
df = pd.concat(out)

阴谋

这看起来不太好,但这只是一个例子

px.line(df,
        x="year",
        y="pop",
        color="country",
        facet_row="continent")

推荐阅读