R语言 如何使用gganimate确保geom_segment()的平滑过渡?

bvhaajcl  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(73)

我试图绘制一个直方图与平均垂直线为每年提供的数据。数据可以在here中找到
代码如下

library(gganimate)
library(ggplot2)
library(dplyr)
data_speed <- readRDS("speed.RDS")
animated_histogram <- data_speed %>%
  ggplot(aes(x = fastestLapSpeed)) +
  geom_histogram(fill = "#ff1801") +
  geom_segment(aes(x = avg_speed, xend = avg_speed, y = 0, yend = Inf),
               color = "blue", size = 1, linetype = "") +
  labs(title = "Year: {frame_time}") +
  transition_time(year) +
  ease_aes('linear')

animate(animated_histogram, fps = 30, duration = 10, width = 500, height = 250)

字符串
根据上面的代码,我得到了下面的图。
x1c 0d1x的数据
如何确保垂直中线(蓝色虚线)平滑过渡,中间没有任何中断?
库版本如下

> packageVersion("gganimate")
[1] ‘1.0.8’
> packageVersion("ggplot2")
[1] ‘3.4.2’
> packageVersion("dplyr")
[1] ‘1.1.2’


提前感谢!

pokxtpni

pokxtpni1#

也许这已经够顺利了。首先,我建议使用geom_vline而不是geom_segment。其次,我使用geom_vline的汇总数据集,其中每年包含一行,而不是像您一样为数据的 * 每行 * 添加一个段或vline:

library(gganimate)
#> Loading required package: ggplot2
library(ggplot2)
library(dplyr)

tmp <- tempfile(fileext = ".RDS")

download.file("https://github.com/adhok/data_sources_new/raw/main/speed.RDS", tmp)

data_speed <- readRDS(tmp)

data_speed_avg <- data_speed |>
  summarise(fastestLapSpeed = mean(fastestLapSpeed), .by = year)

ggplot(data_speed, aes(x = fastestLapSpeed)) +
  geom_histogram(fill = "#ff1801") +
  geom_vline(
    data = data_speed_avg, aes(xintercept = fastestLapSpeed),
    color = "blue", linewidth = 1
  ) +
  labs(title = "Year: {frame_time}") +
  transition_time(year) +
  ease_aes("linear")
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

字符串


的数据

相关问题