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

如何设置geom_col图中各Y变量子组内X轴变量的指定顺序

R ggplot geom_col分组内自定义X轴顺序不生效问题

问题描述

我想要在geom_col图的每个Y变量分组内自定义X轴的变量顺序,找到了使用factor及其水平设置的解决方案,但在我的场景下不生效。

示例数据集

df_full<-data.frame(conc=c(NK, 1 µM X, 1 µM, 10 µM,100 µM,  
                           NK, 1 µM X, 1 µM, 10 µM,100 µM, 
                           NK, 1 µM X, 1 µM, 10 µM,100 µM), 
                    mean=c( 0.9008428,0.8278645,0.7890388,0.9541905, 0.8537885, 0.8212504,1.3828724,0.7165685, 0.7985398, 1.124524, 0.744428,0.835645,0.562878,0.476905, 0.632885), 
                    Treatment=c("A","A","A","A","A", "B", "B", "B","B","B","C","C","C","C", "C"),
                    upper =c(1.0990144, 0.9505348, 0.8273494, 1.0389074, 0.9227461, 
                             0.9657371, 1.6864420, 0.7401891, 0.9046951, 1.0990144, 
                             0.9505348, 0.8273494, 1.0389074,0.7401891, 0.9046951),
                    lower=c(0.7026713, 0.7051941, 0.7507282, 0.9528077, 0.7848309, 
                            0.6767638, 1.0793029, 0.6929479, 0.6923846, 0.7051941,
                            0.6767638, 1.0793029, 0.6929479, 0.7051941, 0.7507282),
                    p.value=c(0.0003, 0.6500, 1,0.02,0.0400, 
                              0.3301,0.100,0.023, 0.05, 0.05,
                              0.0002, 0.86, 0.46, 0.021, 0.001))

异常表现

  • 将conc变量设置为因子后,每个药物分组仅显示2个柱子
  • 不将conc设置为因子,则无法得到conc_factor中定义的顺序

当前绘图代码

legend_title <- "conc"
breaks_y =c(0, 0.25, 0.5, 0.75, 1, 1.25, 1.5)

df_full$Label <- NA
df_full$Label[df_full$p.value<0.001]<-'***'
df_full$Label[df_full$p.value<0.01 & is.na(df_full$Label)]<-'**'
df_full$Label[df_full$p.value<0.05 & is.na(df_full$Label)]<-'*'

conc_factor  = factor(df_full$conc, levels=c("NK", "10 μM X", "1 μM", "10 μM", "100 μM"))

plot <- 
ggplot(df_full, aes(x = factor(Treatment), y = mean, fill = conc_factor)) +
geom_col(color = "black",  position = position_dodge(0.8), width = 0.7) +
geom_errorbar(aes(ymax = upper, ymin = lower), width = 0.27, position = position_dodge(0.8), color = "black", size = 0.7) +
geom_text(aes(label = Label, group = conc_factor),size = 3.7, position = position_dodge(width =0.8), color = "black", vjust =-1.8) +
labs(x = "drug", y = "OD", title = "viability", color = "conc", fill = "conc") +
scale_y_continuous(limits = c(0, 1.5), breaks = breaks_y) +
  theme_bw() +
  theme(axis.text = element_text(size = 12, face = "bold"),
    axis.title.y = element_text(size = 12, face ="bold"),
    axis.title.x = element_text(size = 12, face ="bold")) 

plot + scale_fill_manual(values =  wes_palette("Darjeeling1", n = 5))

需求

如何操作,才能在geom_col的每个Y变量分组内,让X轴按照"NK", "10 μM X", "1 μM", "10 μM", "100 μM"的顺序排列?

解决方案

将代码中所有的μ字符替换为Unicode转义编码\U00B5即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:39:02