如何调整ggplot水平图变量轴顺序,将回归参考类别置于顶部?
解决方法
要让“Standard Job (ref)”显示在图的顶部、“Urban”显示在底部,只需要反转变量因子的水平顺序即可。因为coord_flip()会将x轴转为y轴,而ggplot默认会按照因子水平的顺序从下到上排列y轴标签,把定义的correct_order反转后赋值给因子水平,就能实现需求。
修改后的完整代码如下:
# 创建比值比数据框 odds_ratio_data <- data.frame( Variables = c("Standard Job (ref)", "Precarious job", "Out of labor force", "Unemployed", "Age", "Female", "Non Black and Non Hispanic (ref)", "Black", "Hispanic", "Never Married (ref)", "Married/Cohabiting", "Divorced/Widowed", "Number of children", "Less than High school (ref)", "High school/GED", "College or above", "Both bio parent (ref)", "One bio parent", "Bio and step parent", "Northeast", "North central", "South", "West", "Urban"), OddsRatio = c(1, 1.377127764, 1.150273799, 1.616074402, 0.93239382, 0.923116346, 1, 1.161834243, 1.733253018, 1, 0.121237966, 0.60653066, 0.826959134, 1, 0.93239382, 0.57694981, 1, 0.66365025, 0.486752256, 1, 0.711770323, 0.818730753, 0.835270211, 0.711770323), LowerCI_OR = c(1, 1.173510871, 1.040810774, 1.404947591, 0.913931185, 0.860707976, 1, 1.051271096, 1.419067549, 1, 0.095369162, 0.516851334, 0.778800783, 1, 0.810584246, 0.491644197, 1, 0.548811636, 0.386741023, 1, 0.637628152, 0.733446956, 0.748263568, 0.637628152), UpperCI_OR = c(1, 1.616074402, 1.27124915, 1.858928042, 0.951229425, 0.990049834, 1, 1.284025417, 2.117000017, 1, 0.154123662, 0.711770323, 0.878095431, 1, 1.072508181, 0.677056874, 1, 0.802518798, 0.612626394, 1, 0.786627861, 0.913931185, 0.93239382, 0.786627861) ) # 定义变量顺序,反转后让"Standard Job (ref)"在顶部,"Urban"在底部 correct_order <- c("Standard Job (ref)", "Precarious job", "Out of labor force", "Unemployed", "Age", "Female", "Non Black and Non Hispanic (ref)", "Black", "Hispanic", "Never Married (ref)", "Married/Cohabiting", "Divorced/Widowed", "Number of children", "Less than High school (ref)", "High school/GED", "College or above", "Both bio parent (ref)", "One bio parent", "Bio and step parent", "Northeast", "North central", "South", "West", "Urban") # 反转因子水平顺序 odds_ratio_data$Variables <- factor(odds_ratio_data$Variables, levels = rev(correct_order)) # 绘制水平比值比图 ggplot(odds_ratio_data, aes(x = Variables, y = OddsRatio)) + geom_point(color = "blue", size = 3) + # 绘制比值比点 geom_errorbar(aes(ymin = LowerCI_OR, ymax = UpperCI_OR), width = 0.2) + # 置信区间误差棒 coord_flip() + # 翻转坐标轴为水平图 theme_minimal() + labs(title = "预测NLSY07(2005-2017)年轻成年人同住情况的逻辑回归模型比值比", x = "变量", y = "比值比") + theme(plot.title = element_text(hjust = 0.5), # 标题居中 axis.text.y = element_text(size = 10)) # 调整y轴标签大小
关键修改点
- 在将
Variables转为因子时,使用rev(correct_order)替代原来的correct_order,反转因子水平顺序,配合coord_flip()实现标签从上到下的需求。 - 同步将图表的标题和轴标签翻译成中文,适配中文使用场景。
内容的提问来源于stack exchange,提问作者Quan Mai
相关产品推荐
相关产品推荐

