i have a data frame called df of 2 character variables and one double.
The initial question of the problem i am trying to solve is this here . In a nutshell i am trying to sort in each facet the delta values from lower to higher but also i want to see the my_vars2 values in the y axis.Currently i see only the letters.How can i fix this but still have the same sorting from lower to higher values ?
library(ggplot2)
library(dplyr)
library(forcats)
library(stringr)
## init data --------------------------------------
set.seed(123) # Setting seed for reproducibility
levels <- c('KAMALA-IT', 'HARRIS-HR', 'DONALD-CEO', 'TRUMP-HR', 'BARACK-IT')
my_var <- sample(levels, 50, replace = TRUE)
levels2 <- c('GEORGIA', 'PENNSYLVANIA', 'WINSCOSIN', 'NORTH CAROLINA', 'NEVADA','ARIZONA','MICHIGAN')
my_var2 <- sample(levels2, 50, replace = TRUE)
delta <- rnorm(50, mean = 0, sd = 1)
df <- tibble(my_var,my_var2,delta);df
df <-
group_by(df, my_var) |>
arrange(delta, .by_group = TRUE) |>
mutate(labels = paste0(letters[1:n()], "/", my_var2))
ggplot(df, aes(x = delta, y = labels)) +
geom_point(colour = "red") +
# "free_y" lets the y axis move around between facets
facet_wrap(~my_var, dir = "v", ncol = 1, scales = "free_y") +
# Remove the ordering component of each label:
scale_y_discrete(labels = \(x) str_extract(x, "(?<=/)."))
Simply modify the regex to keep only the state names aka the part of the labels after the separator "/" for which I use gsub
:
library(ggplot2)
ggplot(df, aes(x = delta, y = labels)) +
geom_point(colour = "red") +
facet_wrap(~my_var, dir = "v", ncol = 1, scales = "free_y") +
scale_y_discrete(labels = \(x) gsub("^.*?/", "", x))