Nana
Nana

Reputation: 13

How to fix a dynamic graph made in ggplot2?

I tried to replicate a dynamic graph with the dataframe:

library(tidyverse)
library(gganimate) #may need: devtools::install_github("dgrtwo/gganimate")
library(animation)

df <- data.table::fread(
  "Type       Place  Year  Month1 Month2 Units  Valor
  Segment1   City1  Year1   1      1    192345 1020
  Segment2   City2  Year2   2      14   284590 1597
  Segment3   City3  Year1   3      3    186435 3478
  Segment4   City4  Year3   4      28   269056 1259"
)

ggplot(data = df, aes(x = factor(Year), y = Valor, group = Type, colour = Type)) +
  geom_line(size = 1, show.legend = F) +
  scale_color_manual(values = c("#ff9933", "#006400", "#d11141", "#551A8B")) +
  scale_x_discrete(position = "bottom") +
  scale_y_continuous(labels = NULL)+
  labs(
    title = "NDF- SR",
    x = "Time", y = "Sales"
  ) +
  # geom_text(aes(label=scales::percent(Valor, accuracy = 1),
  # vjust= -2), show.legend = FALSE) +
  theme(plot.title = element_text(hjust = 0.5)) +
  geom_dl(aes(label = value), method = "last.points") +
  transition_reveal(Year) +
  coord_cartesian(clip = "off") +
  ease_aes("cubic-in-out")

animate(p, fps = 7, width = 900, height = 600)
anim_save("election.gif", p)

the error that appears is:

Error: along 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

Upvotes: 0

Views: 1777

Answers (1)

Jon Spring
Jon Spring

Reputation: 66765

A few suggestions:

  • add library(directlabels) at the top or call directlabels::geom_dl.
  • transition_reveal(readr::parse_number(Year)) + since transition_reveal expects a numeric entry and Year is character data like "Year1" and "Year2".
  • p <- ggplot(data = df... so that the ggplot/gganimate object can be animated in the next step.

It's hard to know if this is working, since this doesn't seem to be complete data; you wouldn't typically use geom_line with just one data point per group. Perhaps you could describe more what you're looking for in the question, and/or add more data.

Upvotes: 1

Related Questions