【问题标题】:How to change the scale of a point in an animated plot in R gganimate如何在 R gganimate 中更改动画图中点的比例
【发布时间】:2022-01-11 19:33:43
【问题描述】:

我正在制作一个动画图,在两类数据点中显示三个变量随时间的变化。我需要根据变量之一来缩放可视化中的点,在本例中为 v3。在下面的 MRE 中,这可以正常工作,但我希望我的点更大,比如大 2 到 3 倍,但仍然可以缩放到 v3。如果我设置 geom_point 大小,那么它将以我指定的大小固定点,但它们会根据 v3.3 更改。我还尝试通过 ggplot 代码本身中的某些内容将 v3 相乘,但没有效果。有人可以建议如何做到这一点。

library(ggplot2)
library(gganimate)

#make some data
set.seed(22)
t<-c(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10)
cat<-c("a","a","a","a","a","a","a","a","a","a","b","b","b","b","b","b","b","b","b","b")
v1<-sample(x = 1:10, size  = 20, replace=TRUE)
v2<-sample(x = 1:10, size  = 20, replace=TRUE)
v3<-sample(x=1:5, size = 20, replace=TRUE)
df<-as.data.frame(cbind(t,cat,v1,v2,v3))

df$t<-as.integer(df$t)
df$cat<-as.factor(df$cat)
df$v1<-as.integer(df$v1)
df$v2<-as.integer(df$v2)
df$v3<-as.integer(df$v3)

#build my plot showing size of v3 for categories 'a' and 'b' over time t
p1 <- ggplot(df, aes(v1, v2, size = v3, color = cat, frame = t)) +
labs(x="Variable 1", y = "Variable 2")+ 
ylim(0,10) +
geom_point() +
scale_color_brewer(type = 'div', palette = 'Spectral') + 
# gganimate code
ggtitle("period: {frame_time}") +
transition_time(t) +
ease_aes("linear") +
enter_fade() +
exit_fade()
# animate
animate(p1, width =650, height = 450)

【问题讨论】:

  • 文本中的小错误。应该阅读“如果我设置 geom_point 大小,它将以我指定的大小修复点,但它们不会根据 v3 改变”
  • 您可以通过scale_size(range = ..)设置size的范围,其中range = c(1, 6)是默认值。

标签: r ggplot2 gganimate


【解决方案1】:

好的,我解决了这个问题。感谢 Stefan 建议 scale_size_range。我可以用它来使点变大,但它们没有缩放。但是,通过使用 scale_size_area 并设置 max_size 我可以实现我所需要的。所以在这个非常极端的例子中,使用原始的 MRE 数据集...

#build my plot showing size of v3 for categories 'a' and 'b' over time t
p1 <- ggplot(df, aes(v1, v2, size = v3, color = cat, frame = t)) +
labs(x="Variable 1", y = "Variable 2")+ 
ylim(0,10) +
geom_point() +
scale_color_brewer(type = 'div', palette = 'Spectral') + 
scale_size_area(max_size=40)+
# gganimate code
ggtitle("period: {frame_time}") +
transition_time(t) +
ease_aes("linear") +
enter_fade() +
exit_fade()
# animate
animate(p1, width =650, height = 450)

好的,这会产生一个看起来很奇怪的情节,但它展示了原理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-02
    • 2018-05-28
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2020-10-17
    • 2021-02-23
    相关资源
    最近更新 更多