簡體   English   中英

如何在 python 動畫散點圖 plotly 圖中添加動畫水平線?

[英]How to add an animated horizontal line in a python animated scatter plotly graph?

讓我們以plotly 站點的動畫散點圖為例:

import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])
fig.show()

我想添加一條動畫水平線,代表每年的加權平均預期壽命。 我可以創建一個包含這些加權平均預期壽命的列表:

def weighted_average(df, values, weights):
    # source : https://datagy.io/pandas-weighted-average/
    return sum(df[weights] * df[values]) / df[weights].sum()
L_weighted_average_life_exp = df.groupby('year').apply(weighted_average, 'lifeExp', 'pop').to_list()

我們可以使用add_hline添加一條水平線。 我想我必須遍歷fig.frames但我不知道如何。 我試過類似的東西:

for y,frame in zip(L_weighted_average_life_exp,fig.frames):
   frame.add_hline(y=y, line_width=1, line_dash="dash", line_color="black")

但是 'Frame' object 沒有屬性 'add_hline'。

請問你知道怎么做嗎?

獎勵:在水平線旁邊添加一個注釋,其中包含加權平均預期壽命的數量(因此水平線的 y 軸值)

我找到了一個非最佳解決方案,它包括添加具有line-ew形式的散點:

import plotly.express as px
import pandas as pd
import numpy as np

def weighted_average(df, values, weights):
    return sum(df[weights] * df[values]) / df[weights].sum()

df = px.data.gapminder()

df["Point category"] = "Country"

size = df["pop"].mean()

for index, row in pd.DataFrame(df.groupby('year').apply(weighted_average, 'lifeExp', 'pop')).iterrows():
    i = 100
    while i < df["gdpPercap"].max() :
        for ii in [1,5]:#range(1,10):
            df.loc[df.index.max() + 1] = ["Weighted average life exp %s %s"%(i,ii),"Weighted average life exp",index,row[0],size,i*ii,np.nan,np.nan,"Weighted average life exp"]
        i = i*10

fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55,symbol = df["Point category"],range_x=[100,100000], range_y=[25,90],
           symbol_sequence=["circle","line-ew"],color_discrete_sequence=px.colors.qualitative.Dark24)

fig.update_traces(marker=dict(line=dict(width=1,color='Black')))

fig.show()

我仍然願意接受更好的解決方案在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM