第 7 章 Color

date = lubridate::ymd(c("2020-02-01", "2020-04-01",
  "2020-06-01", "2020-09-01"))
data = list()
data$Britain <- 
  data.frame(
    date = date,
    y = c(0, 50, 80, 100)
  )
data$Spain <-
  data.frame(
    date = date,
    y = c(0, 32, 53, 103)
  )
data$Italy <-
  data.frame(
    date = date,
    y = c(0, 50, 60, 99)
  )
dataAll <- purrr::map_dfr(
  names(data),
  ~{
    cbind(data[[.x]], data.frame(country=.x))
  }
)
  • dataAll is a grouped data

7.1 Group aesthetics

When you have a grouped data frame and intend to draw by groups, you need to set the aesthetics group equal to the group variable in your data frame.

Without group aes:

ggplot(data = dataAll) +
  geom_line(
    aes(
      x = date,
      y = y
    )
  )

With group aes:

ggplot(data = dataAll) +
  geom_line(
    aes(
      x = date,
      y = y,
      group = country
    )
  )

Using aesthetics other than x, y can function as group aesthetic as well:

ggplot(data = dataAll) +
  geom_line(
    aes(
      x = date,
      y = y,
      linetype = country
    )
  )
ggplot(data = dataAll) +
  geom_line(
    aes(
      x = date,
      y = y,
      color = country
    )
  )