python - 如何在 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 次。解决此问题的最佳方法是什么?
解决方案
您可能会考虑读取所有 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")
推荐阅读
- c++ - Qt QOpenGLWidget:调整大小后Skia文本消失
- mule - 在 Mule 中附加和执行动态 OrderBy
- python - django:找不到运行服务器静态文件
- azure-devops - 部署后触发 Azure 管道
- firebase - Firebase手机认证错误信息
- jscript - jscript如果p标签具有特定值并且文本颜色不是红色,如何更改文本颜色
- laravel - 间接修改重载属性 App\Models\frontend\Document::$selfie 无效
- azure-cosmosdb - Cosmos db order by 子句不适用于指数值
- python - Python Flask 未将数据提交到数据库
- kotlin - 有没有办法提示用户输入密码停止锁定任务模式?