Panos Kalatzantonakis
Panos Kalatzantonakis

Reputation: 12683

Outline grouped plot

I would like to outline the shape of the graph produced by a group plot.

Using this code:

# Libraries
library(ggplot2)
library(babynames)
library(dplyr)

# Keep only 3 names
don <- babynames %>% 
  filter(name %in% c("Ashley", "Patricia", "Helen")) %>%
  filter(sex=="F")
  
# Plot
don %>%
  ggplot( aes(x=year, y=n, group=name, color=name)) +
    geom_line()

I get this: grouped plot

Is it possible to keep only the outline of the produced graph? Example output:

Final output

Upvotes: 1

Views: 81

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

There might be a ggplot2 way to do this but here one attempt using dplyr :

library(dplyr)
library(ggplot2)

don %>%
  group_by(year) %>%
  slice(which.max(n)) %>%
  ggplot( aes(x=year, y=n, group=name, color=name)) +
  geom_line()

enter image description here

The logic here is we keep only the row with max n value for each year so it removes all those lines which are being plotted below the outline line that we want.

Upvotes: 2

Related Questions