0

Given the data below, I'm making a simple coefficient plot. I know I could supply a custom order and custom labels to manually rearrange 'var' using scale_y_continuous(), but surely there must be a way to reorder a continuous variable (coef, in my data) within ggplot?

Using the answer here (Plot data in descending order as appears in data frame), with reorder(), gives me the error "invalid argument to unary operator".

Adding to the complication is that I only want the y scale labels to appear once on the far left axis, which means I know I can only sort within one facet. Any ideas how to do this?

ggplot(d, aes(x = coef, y = var)) +
  geom_point(size = 4) +
  facet_wrap(~type,
             nrow = 1,
             scales = "free_x") +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black", size = .3) +
  theme_light()
d < - structure(list(var = c("blue", "green", "yellow", "purple", "orange", 
"blue", "green", "yellow", "purple", "orange"), coef = c(0.2, 
0.05, 0.23, 0.03, -0.15, -0.08, 0.32, -0.03, 0.1, -0.05), type = c("full", 
"full", "full", "full", "full", "half", "half", "half", "half", 
"half")), row.names = c(NA, -10L), spec = structure(list(cols = list(
    var = structure(list(), class = c("collector_character", 
    "collector")), coef = structure(list(), class = c("collector_double", 
    "collector")), type = structure(list(), class = c("collector_character", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x0000024d0c69a340>, class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"))
a_todd12
  • 449
  • 2
  • 12

1 Answers1

1

I like doing this with the forcats package. fct_inorder is a handy function where you just need to get the variables into the order you want (by their first appearance) and then they can become a factor in that order.

library(dplyr)
d |>
  arrange(type, coef) |>
  mutate(var = forcats::fct_inorder(var)) |>
ggplot(aes(x = coef, y = var)) +
  geom_point(size = 4) +
  facet_wrap(~type,
             nrow = 1,
             scales = "free_x") +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black", size = .3) +
  theme_light()

enter image description here


Here's the data I loaded, simplified:

d <- structure(list(var = c("blue", "green", "yellow", "purple", "orange", 
"blue", "green", "yellow", "purple", "orange"), coef = c(0.2, 
0.05, 0.23, 0.03, -0.15, -0.08, 0.32, -0.03, 0.1, -0.05), type = c("full", 
"full", "full", "full", "full", "half", "half", "half", "half", 
"half")), row.names = c(NA, -10L), class = "data.frame")
Jon Spring
  • 55,165
  • 4
  • 35
  • 53