Home > Blockchain >  Adding Consecutive Arrows to geom_point() in ggplot2
Adding Consecutive Arrows to geom_point() in ggplot2

Time:12-19

I want to add a series of arrows connecting each observation in geom_point as in the graph:

Desired Output connecting arrows

I understand that geom_segment is meant to be used, but I am having issues, and have not found something quite like this after quite a bit of searching.

This is sample code that should satisfy the pattern:

Note: The labels are not important ; just the arrows

df <- data.frame(year = c(1935:1968),

                 y_axis_values = c( 2755,2696, 2646, 2701, 2654, 2766, 2832, 2964, 3041, 3010, 3018, 3374, 3545, 3441, 3456, 3455, 3503, 3641, 3721, 3828, 3831, 3858, 3925, 3880, 3935, 3895, 3840, 3756, 3669, 3502, 3145, 2812, 2586,2441),

                 x_axis_values = c(238, 240, 241, 242, 244, 245, 246, 268, 333, 335, 331, 253, 243, 241, 242, 237, 242, 240, 233, 232, 236, 245, 256, 261, 265, 278, 291, 290, 290, 307, 313, 325, 339, 338)


                  

I have tried the general formula with many different argument variations, but cannot seem to find it.

ggplot(df, aes(x = x_axis_values, y = y_axis_values)  
  geom_point()  
  geom_segment() 

CodePudding user response:

You need the xend and yend values for each segment. Since your data frame is in order, the xend and yend value for each segment is just the next row's x and y values. You can get these by using dplyr::lead on the x and y aesthetics.

library(ggplot2)
library(dplyr)

ggplot(df, aes(x = x_axis_values, y = y_axis_values))  
  geom_point(color = "#69b3a2")  
  geom_segment(aes(xend = after_stat(lead(x)), yend = after_stat(lead(y))),
               arrow = arrow(length = unit(3, "mm")), color = "#69b3a2")  
  geom_text(aes(label = year), size = 5, fontface = 2,
            data = . %>% filter(year %in% c(1935, 1937, 1939, 1942, 1945, 1946,
                                            1953, 1957, 1960, 1961)),
            nudge_x = c(-3, -2, 4, 0, 0, -2, -5, 0, 3, 5),
            nudge_y = c(30, -30, 10, -30, -40, -40, 0, -50, 30, 0))  
  labs(x = "partic", y = "tfr")  
  theme_bw(base_size = 16)

enter image description here

  • Related