1

I 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 first column. I want to reorder them by the second column from the smallest value on the bottom and the largest magnitude on top . 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 %>%
  group_by(Quarter, Delay) %>%  
  ggplot(aes(x = Quarter, y =fct_reorder(Weekday,Delay))) + 
  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)

Here in this plot the y-axis is ordered by the "Delay" variable in the first column "Q1", I would like to reorder it by second column which is "Q2". Thank you![enter image description here][1]

Jackie
  • 63
  • 5

1 Answers1

1

Edit: You can use fct_reorder2, where you can add a function that filters Quarter and uses the maximum of Delay to reorder Weekday

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)
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32