'Reorder the data based on one column in ggplot

merged 5 data frame by the r_bind and want to draw a dot plot in ggplot. Based on the code I have the data are ordered based on the second column in the descending order. But what I need, reorder based on second column, where I have all the positive values in the descending order, then the negative values in the descending order of their absolute value, and the last have all the small values. Overall, I want to categorize the data in three group significant positive, significant negative and not significant. And in my bubble ggplot, the top have all the positive significant, then negative significant and the bottom on the plot just not significant. I generate some data to clarify more:

df <- data.frame(
  Weekday = c("Fri", "Tues", "Mon", "Thurs","Mon", "Tues", "Wed", "Fri","Wed", "Thurs", "Fri"),
  Quarter = c(rep("Q1", 3), rep("Q2", 5), rep("Q3",3)),
  Delay = runif(11, -2,5),
  pval = runif(11, 0,1))
df$Quarter <- factor(df$Quarter, levels = c("Q1", "Q2", "Q3"))

df %>%
      mutate(
        Weekday = fct_reorder2(
          .f = Weekday,
          .x = Delay,
          .y = Quarter,
          .fun = function(x,y){mean(x[y=="Q2"])}
        )) %>% 
      ggplot(aes(x = Quarter, y = Weekday)) + 
      geom_point(aes(size = -log10(pval), color = Delay), alpha = 0.8) +
      scale_size_binned(range = c(-2, 12)) +
      scale_color_gradient(low = "mediumblue", high = "red2", space = "Lab")  + 
      theme_bw() +
      theme(axis.text.x = element_text(angle = 25, hjust = 1, size = 10)) +
      ylab(NULL) + xlab(NULL)

Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source