Paula
Paula

Reputation: 703

ggplot2: conditionally changing linetype and color

I have the following dataframe:

df <- tribble(
  ~group,             ~year,   ~value,  
  "group1",     "2010-2015",       70,
  "group2",     "2010-2015",       75,
  "group1",     "2015-2020",       72,
  "group2",     "2015-2020",       77,
  "group1",     "2020-2025",       74,
  "group2",     "2020-2025",       79,
  "group1",     "2025-2030",       76,
  "group2",     "2025-2030",       81)

I want to plot as x, year, and as y, value, colored by group, i.e,

ggplot(df, aes(year, value, color = group, group = group)) +
  geom_line(size = 1.1)

But I want the years "2020-2025" and "2025-2030" to be dashed lines.

Using the following code I get this error: "Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line"

df %>% 
  mutate(projection = year %in% c("2020-2025", "2025-2030")) %>% 
  ggplot(aes(year, value, color = group, group = group)) +
  geom_line(aes(linetype = projection), size = 1.1)

Upvotes: 1

Views: 548

Answers (2)

ekoam
ekoam

Reputation: 8844

Try this perhaps

library(tidyr)
library(dplyr)
library(ggplot2)

df %>% 
  mutate(projection = list("2010-2015" = F, "2015-2020" = c(T, F), "2020-2025" = T, "2025-2030" = T)[year]) %>% 
  unnest(projection) %>% 
  ggplot(aes(year, value, color = group, group = interaction(group, projection))) +
  geom_line(aes(linetype = projection), size = 1.1)

Output

enter image description here


Another form

df %>% 
  mutate(projection = list("2010-2015" = F, "2015-2020" = F, "2020-2025" = c(T, F), "2025-2030" = T)[year]) %>% 
  unnest(projection) %>% 
  ggplot(aes(year, value, color = group, group = interaction(group, projection))) +
  geom_line(aes(linetype = projection), size = 1.1)

Output

enter image description here

Upvotes: 3

stefan
stefan

Reputation: 125617

This could be achieved via two geom_line layers and filtering the data to be displayed by each:

library(tidyverse)

df <- tribble(
  ~group,             ~year,   ~value,  
  "group1",     "2010-2015",       70,
  "group2",     "2010-2015",       75,
  "group1",     "2015-2020",       72,
  "group2",     "2015-2020",       77,
  "group1",     "2020-2025",       74,
  "group2",     "2020-2025",       79,
  "group1",     "2025-2030",       76,
  "group2",     "2025-2030",       81)

df1 <- df %>% 
  mutate(projection = year %in% c("2020-2025", "2025-2030"))

ggplot(mapping = aes(year, value, color = group, group = group)) +
  geom_line(data = filter(df1, !year %in% c("2025-2030")), size = 1.1) +
  geom_line(data = filter(df1, projection), size = 1.1, linetype = "dashed")

Upvotes: 0

Related Questions