为了说明我的问题,我使用了他们网站上包含的示例 Plotly 动画图表:
https://plotly.com/python/animations/
原始代码:
df = px.data.gapminder()
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])
它显示了所有国家,但是当我们删除有关 1970 年以前的欧洲国家的数据时,欧洲不会显示在图例中。
当我删除有关亚洲国家的数据时,情况更糟。即使它具有剩余大陆的完整数据,它也会更改帧范围。
当它出现在至少一帧中时,如何强制此图表始终在 Legend 中包含一个大陆?
import plotly.express as px
df = px.data.gapminder()
df = df.drop(df[(df.continent == 'Europe') & (df.year < 1970)].index) #here I remove data
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])```
[1]: https://i.stack.imgur.com/5rci1.png
情节动画存在局限性,因为预期尺寸是一致的。这可以通过进行适当的外部连接来实现,以确保所有组合都存在。以您的示例代码为起点,然后使用pandas确保在做之前有尺寸一致性px.scatter()
import pandas as pd
import plotly.express as px
df = px.data.gapminder()
df = df.drop(df[(df.continent == 'Europe') & (df.year < 1970)].index) #here I remove data
# ensure all combinations of attributes are present
key_cols = ["continent", "year", "country"]
df2 = pd.DataFrame(
index=pd.MultiIndex.from_product(
[df[col].unique() for col in key_cols], names=key_cols
)
).merge(df, on=key_cols, how="left")
# an insignificatly small value
df2["pop"] = df2["pop"].fillna(.001)
px.scatter(df2, 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])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句