考虑下面的数据集:三个变量和一个分类性别变量一起使用
#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)现在,我意识到如何从这里的代码中生成一个类似的图形。
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然而,我想知道是否有办法重新排序比较?例如,在抑郁和焦虑之前(图中从左到右)的外向性比较。目前,它默认为第一个面板中的焦虑。
我通常会在forcats包中做类似的事情,但是我只使用单个变量来完成。也许有什么办法来安排这些面板?
发布于 2022-06-27 18:47:47
您可以在factor中创建"name“列,在该列中,您可以按照以下代码在mutate中订购levels:
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输出:

https://stackoverflow.com/questions/72776964
复制相似问题