简体   繁体   中英

How do I create a plot with 6 line subplots in plotly?

I have 6 different data frames and I would like to make 1 figure displaying 6 graphs with year on the x axis and incident cases per 100k on the y axis for each. I have been using the following code to create a single graph that I desire, but now I am stuck on how to get them all into 1 figure.

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

I simply want this plot 6 times using 6 different data frames (ie gyeEUR, gyeEMR....). What is the best way to go about this?

You might consider to read all 6 dataframes, add a column to them df_i["fn"]= "filename" and finally concat them to a bigger dataframe df and use

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

Update: full example

Generate data

Here we simply read the data for gapminder builted-in plotly.express and split in several files for continent. Given that the continent is in the file name we drop that column inside every group

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))

Read data and concat

# 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)

Plot

This doesn't look that good but it's just an example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM