Home > Mobile >  How to order paths in geom_link based on the difference between xend and x values?
How to order paths in geom_link based on the difference between xend and x values?

Time:09-16

The below code produces a basic plot using geom_link. I'm wondering how I can order the paths/segments by the ex_data$x_diff variable or by the difference between xend and x points? I'd like to have those segments with the largest positive difference between xend and x appear towards the top of the plot and vice versa for the negative differences between xend and x.

Thanks.

library(tidyverse)
library(ggforce)

ex_data <- data.frame(
  id = letters[1:16],
  x = c(9.17, 11.81, 0.95, 5.61, 2.52, 1.78, 1.44, 2.40, 5.14, 8.25, 6.65, 4.44,
        2.71, 2.35, 2.20, 6.76),
  xend = c(3.87, 10.75, 6.82, 10.11, 3.67, 4.28, 4.99, 2.69, 7.01, 4.90, 8.64,
           1.48, 0.20, 0.32, 2.16, 4.55),
  colour = c("#97233f", "#241773", "#0b162a", "#fb4f14", "#002244", "#002244",
             "#203731", "#000000", "#002244", "#008e97", "#4f2683", "#203731",
             "#004953", "#000000", "#002244", "#aa0000")
)

ex_data$x_diff <- ex_data$xend - ex_data$x

ggplot(ex_data)  
  geom_link(aes(x = x, xend = xend, y = id, yend = id, colour = colour,
                alpha = stat(index)), show.legend = FALSE, size = 5, n = 500)  
  scale_colour_identity()

CodePudding user response:

One option to achieve your desired result would be to reorder your id variable according to x_diff:

library(tidyverse)
library(ggforce)

ex_data$x_diff <- ex_data$xend - ex_data$x
ex_data$id <- reorder(ex_data$id, ex_data$x_diff)

ggplot(ex_data)  
  geom_link(aes(x = x, xend = xend, y = id, yend = id, colour = colour,
                alpha = stat(index)), show.legend = FALSE, size = 5, n = 500)  
  scale_colour_identity()

  • Related