2

我有 geom_line 图(使用空气质量数据作为可重复的例子)显示温度变化,每月一条线,然后以这种方式 gganimate:

library("tidyverse")
library("gganimate")
data("airquality")

ggplot(airquality, aes(Day, Temp, color = Month)) +
     geom_line(size = 2) +
     geom_dl(aes(label = Month), method = list(dl.trans(x = x + 0.1, y = y + 0.25), "last.points", fontface = "bold")) +
     transition_time(Month) +
     labs(title = 'Month is {frame_time}') +
     shadow_mark(aes(color = Month),size=1, alpha=0.7, past=T, future=F) +
     geom_path(aes(color = Month), size = 1)

渲染此动画:

在此处输入图像描述

我的主要问题是实现相同但显示月份名称而不是数字(允许我在标签和标题中放置月份名称)摆脱连接每行开头和结尾的直线。我试过这个(到目前为止没有成功):

aq <- airquality %>%
      dplyr::mutate(Month = month.name[Month])

ggplot(aq, aes(Day, Temp, color = Month)) +
  geom_line( size = 1) +
  geom_dl(aes(label = Month), method = list(dl.trans(x = x + 0.1, y = y + 0.25), "last.points", fontface = "bold")) +
  transition_time(Month) +
  labs(title = month.name['{frame_time}']) +
  shadow_mark(size = 1, colour = 'grey') +
  geom_path(aes(group = Month), size = 1)

Error: time data must either be integer, numeric, POSIXct, Date, difftime, orhms
In addition: Warning messages:
1: In min(cl[cl != 0]) : no non-missing arguments to min; returning Inf
2: In min(cl[cl != 0]) : no non-missing arguments to min; returning Inf
3: In min(cl[cl != 0]) : no non-missing arguments to min; returning Inf
4

1 回答 1

1

将您的月份名称设置为新变量,并将其用于label. 然后你可以使用transition_states而不是transition_time,它只需要数字、整数或日期/时间。您可以设置一个完整的日期列并在 中使用它transition_time,但使用起来transition_states非常简单。如果你走这条路,你需要为你的关卡排序,否则它会按字母顺序排列它们states

library("tidyverse")
library("gganimate") # devtools::install_github("thomasp85/gganimate")
library("directlabels")
library("transformr") # devtools::install_github("thomasp85/transformr")
data("airquality")

aq <- airquality %>%
  dplyr::mutate(MonthName = month.name[Month])

aq$MonthName <- factor(aq$MonthName, levels = c("May", "June", "July", "August", "September"))

ggplot(aq, aes(Day, Temp, color = Month)) +
  geom_line( size = 1) +
  geom_dl(aes(label = MonthName), method = list(dl.trans(x = x + 0.1, y = y + 0.25), "last.points", fontface = "bold")) +
  transition_states(MonthName, transition_length = 3, state_length = 1) +
  labs(title = 'Month is {closest_state}') +
  shadow_mark(size = 1, colour = 'grey') +
  geom_path(aes(group = MonthName), size = 1)

于 2018-11-29T16:44:10.913 回答