You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R的ggplot中交换两个箱线图的显示顺序?

交换箱线图位置的解决方案

有两种简单方法可以实现将Any_Enrichment_Control放在左侧、Any_Enrichment放在右侧的需求:

方法1:调整数据选择顺序

在dplyr::select()中调换两个变量的顺序,这样pivot_longer生成的Variable列顺序会随之改变,箱线图的位置也就交换了。注意要同步调整geom_boxplot的填充色顺序,保证每个变量的颜色对应正确:

data3 %>% 
  dplyr::select(Any_Enrichment_Control, Any_Enrichment) %>%  # 交换变量顺序
  pivot_longer(cols = everything(), names_to = "Variable", values_to = "Value") %>%
  ggplot(aes(x= Variable, y = Value, fill = Variable)) +
  stat_boxplot(geom= "errorbar", width= 0.5) +
  geom_boxplot(fill=c("cadetblue3", "#fa9d5a"))+  # 同步交换填充色
  labs(x="", y="Frequency (total)", title="Stay on enclosure site - Any enrichment")+
  theme_minimal()+
  theme(axis.title.x = element_text(size =16))+
  theme(axis.title.y = element_text(size =16))+
  theme(plot.title=element_text(size = 17))+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.text.x = element_text(size = 13, color="black"))+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(plot.title = element_text(vjust = 1.5))+
  theme(axis.title.y =element_text(vjust = 2))+
  stat_summary(fun = mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..),
               width = .75,lwd = 0.5, linetype = "dashed", col = "red") +
  #scale_x_discrete(labels = c("Enrichment absent", "Enrichment present"))+
  ylim(0,30) 

方法2:用scale_x_discrete强制指定顺序

如果不想修改数据处理流程,可以直接在ggplot图层中添加scale_x_discrete(limits = ...)来指定x轴的显示顺序,同样需要同步调整填充色:

data3 %>% 
  dplyr::select(Any_Enrichment, Any_Enrichment_Control) %>%
  pivot_longer(cols = everything(), names_to = "Variable", values_to = "Value") %>%
  ggplot(aes(x= Variable, y = Value, fill = Variable)) +
  stat_boxplot(geom= "errorbar", width= 0.5) +
  geom_boxplot(fill=c("cadetblue3", "#fa9d5a"))+  # 交换填充色顺序
  labs(x="", y="Frequency (total)", title="Stay on enclosure site - Any enrichment")+
  theme_minimal()+
  theme(axis.title.x = element_text(size =16))+
  theme(axis.title.y = element_text(size =16))+
  theme(plot.title=element_text(size = 17))+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.text.x = element_text(size = 13, color="black"))+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(plot.title = element_text(vjust = 1.5))+
  theme(axis.title.y =element_text(vjust = 2))+
  stat_summary(fun = mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..),
               width = .75,lwd = 0.5, linetype = "dashed", col = "red") +
  scale_x_discrete(limits = c("Any_Enrichment_Control", "Any_Enrichment")) +  # 指定x轴顺序
  #scale_x_discrete(labels = c("Enrichment absent", "Enrichment present"))+
  ylim(0,30) 

两种方法都能达到你想要的效果,根据自己的习惯选择即可。

内容的提问来源于stack exchange,提问作者N3st0r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:53:21