如何为带误差棒的点图重新排序分类Y轴
问题:ggplot2中Y轴(VM)无法按指定顺序排列

当前使用的绘图代码
ggplot(data = TI, aes(y = VM, x = GeoM)) + geom_point() + geom_errorbar(mapping = aes(xmin = L95, xmax = U95), width = .75) + geom_vline(aes(xintercept = 1), linetype = "dashed") + scale_x_continuous(breaks = seq(.2, 1.7, .1)) + scale_y_discrete()
数据集TI
VM GeoM L95 U95 CT1 1.044493 0.8411629 1.296973 CT2 1.1004184 0.843248 1.43602 CT3 1.0081634 0.8162887 1.24514 CT4 1.0621437 0.7885893 1.430591 CT5 0.9211109 0.6730119 1.260669 CT6 0.9704301 0.7795527 1.208045 CT7 0.8890728 0.6610186 1.195807 CT8 0.9366766 0.7370134 1.19043 US1 0.5968839 0.213126 1.671642 US2 0.5991981 0.21634 1.659603
已尝试的方法
- 将VM转为因子/有序因子,配合
scale_y_discrete()的limits/breaks/labels参数指定顺序:scale_y_discrete( limits=c("CT1","CT2","CT3","CT4","CT5","CT6","CT7","CT8", "US1","US2") )scale_y_discrete( breaks=c("CT1","CT2","CT3","CT4","CT5","CT6","CT7","CT8", "US1","US2") )scale_y_discrete( labels=c("CT1","CT2","CT3","CT4","CT5","CT6","CT7","CT8", "US1","US2") ) - 将
aes放入geom_point中 - 使用dplyr排序后重新指定因子水平:
TI %>% arrange(VM) %>% mutate(VM = factor(VM, levels = VM)) %>% ggplot(aes(y = VM, x = GeoM)) + geom_point() + geom_errorbar(mapping = aes(xmin = L95, xmax = U95), width = .75) + geom_vline(aes(xintercept = 1), linetype = "dashed")
所有操作均无报错,但Y轴顺序始终未改变,求解决方案。
解决方案
问题核心是:ggplot2默认会对字符型变量按字母顺序排序,而你之前用arrange(VM)是按VM的字母顺序排序,和原始数据顺序不符。直接手动指定因子水平即可,关键是在绘图前就把VM转为因子并明确指定levels:
方法1:提前修改数据集
# 手动指定VM的因子水平为原始数据顺序 TI$VM <- factor(TI$VM, levels = c("CT1","CT2","CT3","CT4","CT5","CT6","CT7","CT8", "US1","US2")) # 正常绘图 ggplot(data = TI, aes(y = VM, x = GeoM)) + geom_point() + geom_errorbar(mapping = aes(xmin = L95, xmax = U95), width = .75) + geom_vline(aes(xintercept = 1), linetype = "dashed") + scale_x_continuous(breaks = seq(.2, 1.7, .1))
方法2:用dplyr链式操作直接指定水平
TI %>% mutate(VM = factor(VM, levels = c("CT1","CT2","CT3","CT4","CT5","CT6","CT7","CT8", "US1","US2"))) %>% ggplot(aes(y = VM, x = GeoM)) + geom_point() + geom_errorbar(mapping = aes(xmin = L95, xmax = U95), width = .75) + geom_vline(aes(xintercept = 1), linetype = "dashed") + scale_x_continuous(breaks = seq(.2, 1.7, .1))
方法3:直接沿用数据框原始行顺序
如果不想手动写levels列表,可以直接用原始数据的VM列顺序作为因子水平:
TI$VM <- factor(TI$VM, levels = TI$VM)
以上三种方法都能让Y轴严格按照你原始数据中VM的顺序排列。
内容的提问来源于stack exchange,提问作者user26398718
相关产品推荐
相关产品推荐

