繁体   English   中英

在动画 plotly 散点图 plot 中,如何更改每帧的轴比例......但在 R 中? (适配python方案?)

[英]In an animated plotly scatter plot, how to change the axis scale per frame... but in R? (adapt a python solution?)

我正在尝试在 R 内制作一个动画 plotly 图,其中两个轴的最小值和最大值在 animation 期间发生变化。最近有人针对 python 问了这个确切的问题,它通过使用布局更新和循环“帧”来解决。

Python 解决方案在这里: 有没有办法动态改变每帧 plotly animation 轴比例?

这是 python 代码。

import plotly.express as px
df = px.data.gapminder()
df = df[(df['continent'] == 'Asia') & (df['year'].isin([1997, 2002, 2007]))]

scales = [2002]

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

yranges = {2002:[0, 200]}

for f in fig.frames:
    if int(f.name) in yranges.keys():
        f.layout.update(yaxis_range = yranges[int(f.name)])

fig.show()

我一直在查看 R 示例和 R plotly object 示例,但我无法弄清楚......我将如何将此解决方案应用于 R?

这里有一个使用 Shiny 的解决方案,但是 animation 不太流畅,它没有 slider,而且我对 shiny 一无所知,所以我宁愿避免使用它: https://community。 plotly.com/t/what-is-the-most-performant-way-to-update-a-graph-with-new-data/639/6?u=fabern

如果它有用,我编写了我的代码以开始在 R 中重新创建示例……尽我所能。也许我需要使用 plotly express 或 dash 或类似的东西?

library("gapminder")
library('data.table')
  data(package = "gapminder")
  df <- as.data.table(as.data.frame(gapminder))
  df <- df[continent=='Asia' & year %in% c(1997, 2002, 2007)]
  
  graph_animated <- plot_ly(df, x = ~gdpPercap, y = ~lifeExp, frame = ~year, size = ~pop,
                            type = 'scatter', color = ~continent)

最简单的方法是构建 plot,然后添加更改。 您必须先构建,才能看到要修改的框架。

# build
plt <- plotly_build(graph_animated)

# modify the layout for the second frame
plt$x$frames[[2]]$layout = list(yaxis = list(range = c(0, 200)))

之后,您可以像想象任何其他 plot 一样想象它。

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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