Plotly。如何在一个图中输出多个线图?

问题描述 投票:1回答:1

我想用plotly在一个图中绘制多个数据帧的线图,我的代码是。

import plotly.express as px
labels=category_names[:10]
for category in category_names[:10]:
    df_b=df1[df1['Country/Region']==category]    
    fig=px.line(df_b, x="Date", y="Confirmed",labels="Country/Region") 
    print(category)    
fig.show()

然而,通过使用上面的代码,我只能得到for循环最后一次迭代的线图。

当前输出。

enter image description here

希望的输出。

enter image description here

请帮助我的代码!

python dataframe for-loop plotly linegraph
1个回答
3
投票

使用 plotly.expresspx.line(),你不应该使用 for loop 只要你的数据集是一个数据集,就可以在一个图中输出多行。long 格式。您可能会把这种方法与使用 for loopfig.add_figure()的数据,这可以说是更适合于具有以下特点的数据 wide 格式,其中你会把国家作为列名,把时间作为索引,并在你的数据框架中设置一个单一类别的值。

如果没有一个合适的数据样本,就不容易100%肯定地判断你的问题是什么。但在我看来,你的数据结构似乎符合 px.data.gapminder()

    country continent   year    lifeExp pop         gdpPercap   iso_alpha   iso_num
0   Afghanistan Asia    1952    28.801  8425333     779.445314  AFG 4
1   Afghanistan Asia    1957    30.332  9240934     820.853030  AFG 4
2   Afghanistan Asia    1962    31.997  10267083    853.100710  AFG 4
3   Afghanistan Asia    1967    34.020  11537966    836.197138  AFG 4
4   Afghanistan Asia    1972    36.088  13079460    739.981106  AFG 4

所以,我会根据这个问题提供一个答案,你可以试着从那里整理一下。当然,除非你愿意分享一个完整的数据样本和代码片段。

Plot。

enter image description here

完整的代码

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd

# sample dataset from plotly express
df = px.data.gapminder()

# Filter and pivot dataset for each country,
# and add lines for each country
fig = go.Figure()
for c in df['country'].unique()[:3]:
    dfp = df[df['country']==c].pivot(index='year', columns='country', values='pop') 
    fig.add_traces(go.Scatter(x=dfp.index, y=dfp[c], mode='lines', name = c))

fig.show()

这段代码的作用是,将源数据分门别类,比如:

    country continent   year    lifeExp pop gdpPercap   iso_alpha   iso_num
564 Germany Europe  1952    67.5    69145952    7144.114393 DEU 276
565 Germany Europe  1957    69.1    71019069    10187.826650    DEU 276
566 Germany Europe  1962    70.3    73739117    12902.462910    DEU 276
567 Germany Europe  1967    70.8    76368453    14745.625610    DEU 276
568 Germany Europe  1972    71.0    78717088    18016.180270    DEU 276

...然后利用数据集的数据透视功能... df[df['country']=='Germany'].pivot(index='year', columns='country', values='pop') 要得到。

country Germany
year    
1952    69145952
1957    71019069
1962    73739117
1967    76368453
1972    78717088
1977    78160773
1982    78335266
1987    77718298
1992    80597764
1997    82011073
2002    82350671
2007    82400996

...和 然后 将这些数据添加到一个plotly图中,使用 fig.add_traces() .

© www.soinside.com 2019 - 2024. All rights reserved.