Home > Enterprise >  ggplot2 geom_segment by group
ggplot2 geom_segment by group

Time:03-05

I am trying to draw separate line segments for each of the countries (A, B, C) in the plot.

I used the variable country for the group argument (as the docs suggest), but that does not work. The line is still a continuous line connecting all the text labels, but I need 3 separate lines to be drawn, one for each country, connecting the 3 text labels across the years.

library(dplyr)
library(ggplot2)

df_p <- data.frame(
  year = rep(2019:2021, each = 3),
  country = rep(LETTERS[1:3], 3),
  var_a = c(1,6,10,2,5,7,3,7,9),
  var_b = c(2,8,14,4,9,15,2,9,19)
)

df_p %>% arrange(country, year) %>% 
ggplot(aes(x = var_a, y = var_b, color = country))  
  geom_text(aes(label = year))  
  geom_segment(
    aes(
      xend = c(tail(var_a, n = -1), NA), 
      yend = c(tail(var_b, n = -1), NA), 
      group = country
    ),
    arrow = arrow(type = "open", length = unit(0.15, "inches"))
  )

CodePudding user response:

I think you just need geom_path instead of geom_segment.

Try this:

df_p %>% arrange(country, year) %>% 
  ggplot(aes(x = var_a, y = var_b, color = country))  
  geom_text(aes(label = year))  
  geom_path(
    aes(
      group = country
    ),
    arrow = arrow(type = "open", length = unit(0.15, "inches"))
  )

CodePudding user response:

Another possible solution with geom_polygon() without showing the direction of the connections:

Sample data:

    df_p <- data.frame(
      year = rep(2019:2021, each = 3),
      country = rep(LETTERS[1:3], 3),
      var_a = c(1,6,10,2,5,7,3,7,9),
      var_b = c(2,8,14,4,9,15,2,9,19)
    )

Sample code:

library(dplyr)
library(ggplot2)

 df_p %>% 
   arrange(country, year) %>% 
   ggplot(aes(x = var_a, y = var_b, group = country))  
   geom_point(aes(colour = country, shape = country), size = 4)  
   geom_line(aes(colour = country), size = 1) 
   geom_text(aes(label = year))  
   geom_polygon(
    aes(
      fill= country), alpha = .4) 
  labs(x="Variable B",y="Variable A") 
   theme_bw()

Output:

enter image description here

  • Related