2

I have geom_line plot (using airquality data for reproducible example) showing temperature changes, a line per month, and then gganimate this way:

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)

Rendering this animation:

enter image description here

My main issue is to achieve the same but showing Month names instead of numbers (allowing me to puth Month Name in label and Title) and get rid of the straight line that connected beginning and ending of every line. I've tried this (no success so far):

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
Forge
  • 1,587
  • 1
  • 15
  • 36

1 Answers1

1

Set your month name as a new variable, and use that for the label. Then you can use transition_states instead of transition_time, which takes only numeric, integer, or date/time. You could set a full date column and use that in transition_time, but using transition_states is pretty easy. You'll need to order your levels if you go this route, otherwise it'll order them alphabetically as 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)

Anonymous coward
  • 2,061
  • 1
  • 16
  • 29