Considering the dataset below: Three variables alongside a categorical sex variable
#Example Data
Extraversion <- c(4.3, 2, 4.2, 4, 2, 1.5, 3.8, 3.5, 2.1, 2.1, 3)
Anxiety <- c(1.2, 3, 1, 2.3, 5, 5, 2.3, 2.2, 5, 4.5, 3)
Depression <- c(2, 3.5, 1, 3.5, 5, 5, 1, 2, 4.3, 4.5, 1)
Sex <- c("Male", "Female", "Male", "Male", "Female", "Female", "Male",
"Female", "Female", "Female", "Male")
data <- data.frame(Extraversion, Anxiety, Depression, Sex)
Now, I realize how I would make a graph like the one from the code here.
library(ggpubr)
library(ggplot2)
library(ggsci)
data %>% #specifies dataset
pivot_longer(-Sex) %>% #Pivotes graph longways
ggbarplot(x = "Sex", #Splitting variable
y = "value", #Just call this value, its the value on the x axis
facet.by = "name", #selects variables for comapirson leave "name"
add = c("mean_se", "jitter"),, #Creates error bars, Adds data points jittered
width = .99, #Edits wdith of bars
size = .2, #Border thickness
error.plot = "errorbar",
add.params = list(size = .1, alph = .3), #changes size of points and alpha level
color = "black",
fill = "Sex", #Fills colors by Sex variable
alpha = .7, #Alpha for bar fill color
palette = "jama", #ggsci palette
position = position_dodge())
theme_classic2() #theme
However, I was wondering if there was a way to reorder the comparisons? For example, the comparison for Extraversion before depression and anxiety (from left to right in the graph). At the moment it defaults as Anxiety in the first panel.
I've would typically do something like this with the forcats
package, but I've only every done it with single variables. Perhaps some way to arrange the panels?
CodePudding user response:
You can create the "name" column in a factor
where your order the levels
like in the mutate
in the following code:
library(ggpubr)
library(ggplot2)
library(ggsci)
data %>% #specifies dataset
pivot_longer(-Sex) %>% #Pivotes graph longways
mutate(name = factor(name, levels = c("Extraversion", "Depression", "Anxiety"))) %>%
ggbarplot(x = "Sex", #Splitting variable
y = "value", #Just call this value, its the value on the x axis
facet.by = "name", #selects variables for comapirson leave "name"
add = c("mean_se", "jitter"),, #Creates error bars, Adds data points jittered
width = .99, #Edits wdith of bars
size = .2, #Border thickness
error.plot = "errorbar",
add.params = list(size = .1, alph = .3), #changes size of points and alpha level
color = "black",
fill = "Sex", #Fills colors by Sex variable
alpha = .7, #Alpha for bar fill color
palette = "jama", #ggsci palette
position = position_dodge())
theme_classic2() #theme
Output: