R语言ggplot绘图中Y轴文本换行后排序错乱的技术问询
Hey, I see exactly what's going on here—let's break this down and fix it quickly!
问题根源
When you run stringr::str_wrap(qtxt4.1, width = 35), you're taking your ordered factor qtxt4.1 and converting it straight to a character vector. The problem? Ordered factors store their custom sort order in their levels attribute, and once you convert to plain text, that sort information gets completely lost. ggplot then defaults to sorting the Y-axis alphabetically instead of using your original Q1-Q17 order.
解决方案
The fix is simple: keep your original ordered factor for the Y-axis mapping (so ggplot respects your custom order), and just use the wrapped text as the axis labels instead of replacing the factor itself. Here's how to adjust your code:
- First, keep both the ordered factor and the wrapped text in your
questions4data frame:
# 保留原始有序因子qtxt4.1,同时添加换行后的文本列qtxt4.2 questions4 <- data.frame(qnum4, qtxt4.1) questions4$qtxt4.2 <- stringr::str_wrap(questions4$qtxt4.1, width = 35)
- Then, in your ggplot call, map the Y-axis to the original ordered factor
qtxt4.1, and usescale_y_discrete()to set the labels to your wrapped text:
df_c2 %>% pivot_longer(-Studies, names_to = "qnum4") %>% left_join(questions4, by = "qnum4") %>% ggplot(aes(value, qtxt4.1)) + # 这里用原始有序因子映射Y轴 geom_point(aes(color = Studies)) + labs(x = NULL, y = NULL) + scale_x_continuous(limits = c(1, 5)) + # 用换行后的文本作为Y轴标签 scale_y_discrete(labels = questions4$qtxt4.2) + theme(text = element_text(size = 12), axis.text = element_text(size = 10))
为什么这样管用?
By mapping to qtxt4.1 (your ordered factor), ggplot uses the custom level order you defined earlier. The scale_y_discrete(labels = ...) argument just replaces the displayed text with your wrapped lines—without touching the underlying sort order.
另一种简化方式
If you prefer, you can also handle the labels directly in the axis.text.y theme element, but using scale_y_discrete is cleaner and more explicit for this use case.
内容的提问来源于stack exchange,提问作者Coxy_cox

