簡體   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