删除直线并使用ggplot + gganimate将标签/标题设置为月份名称而不是数字

时间:2018-11-29 12:51:21

标签: r ggplot2 gganimate

我有geom_line图(使用空气质量数据作为可再现示例),显示温度变化,每月显示一条线,然后以这种方式进行动画处理:

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)

渲染此动画:

enter image description here

我的主要问题是要达到相同的目的,但显示月份名称而不是数字(允许我在标签和标题中显示月份名称),并摆脱连接开始的直线和每一行的结尾。 我已经尝试过了(到目前为止没有成功):

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

1 个答案:

答案 0 :(得分: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)