[英]How to add an animated horizontal line in a python animated scatter plotly graph?
Let's take a sample example of animated scatter graph from plotly site :让我们以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()
I would like to add an animated horizontal line that represents the weighted average life expectancy for each year.我想添加一条动画水平线,代表每年的加权平均预期寿命。 I can create a list with those weighted average life expectancy like that:我可以创建一个包含这些加权平均预期寿命的列表:
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()
We can add an horizontal line using add_hline .我们可以使用add_hline添加一条水平线。 I guess that I have to iterate over fig.frames
but I don't know how.我想我必须遍历fig.frames
但我不知道如何。 I tried something like:我试过类似的东西:
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")
But 'Frame' object has no attribute 'add_hline'.但是 'Frame' object 没有属性 'add_hline'。
Would you know please how to do?请问你知道怎么做吗?
Bonus: add an annotation next to the horizontal line with the amount of the weighted average life expectancy (so the value of y-axis of the horizontal line)奖励:在水平线旁边添加一个注释,其中包含加权平均预期寿命的数量(因此水平线的 y 轴值)
I found a non-optimal solution, which consists in adding scatters having the form line-ew
:我找到了一个非最佳解决方案,它包括添加具有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.