I want to customize x-axis label in ggplot2.
library(tidyverse)
set.seed(1)
df = data.frame(SUBJID = 1001:1010,
Level = sample(c("Normal", "Mild", "Moderate", "Severe"), 10, replace = T),
Value = runif(10, min = 200, max = 500))
df %>%
ggplot(aes(Level, Value)) +
geom_boxplot()
For known X label, usually I use this code to change order.
df$Level = factor(df$Level, levels = c("Normal", "Mild", "Moderate", "Severe"))
df %>%
ggplot(aes(Level, Value)) +
geom_boxplot()
But I added the subject number in X label, so the label is not a known character.
df %>%
group_by(Level) %>%
mutate(
SUBJN = n_distinct(SUBJID),
Level_N = paste(Level, "(N=", SUBJN, ")")
) %>%
ggplot(aes(Level_N, Value)) +
geom_boxplot()
The X label is not a fixed character, so I cannot use the code I previously used.
How to customize order of X label in this situation?
I tried fct_reorder, and the plot was not what I wanted.
df %>%
group_by(Level) %>%
mutate(
SUBJN = n_distinct(SUBJID),
Level_N = paste(Level, "(N=", SUBJN, ")") |> factor() |> fct_reorder(as.numeric(Level))
) %>%
boxplot(Value ~ Level_N)