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

R语言绘制箱线图如何实现x轴1到10的连续数值排序

问题根因

Pos_in_turn列为字符类型,R的字符排序规则为字典序,因此"10"会排在"2"之前,导致x轴顺序不符合数字连续顺序。


通用解决方案(适配base R和ggplot2)

将Pos_in_turn转换为有序因子,手动指定层级为1到10的数字顺序,修改后原有绘图代码无需调整即可得到正确顺序的x轴:

well$Pos_in_turn <- factor(well$Pos_in_turn, levels = as.character(1:10))

不修改原始数据集的临时方案

1. base R 绘图调整

在boxplot函数中手动指定分组位置和标签:

boxplot(d ~ Pos_in_turn, data = well,
        at = 1:10,
        labels = as.character(1:10),
        main = "How long does it take to say 'well'?\n(in 10-word turns from BNC-C)", 
        cex.main = 0.9,
        xlab = "Position in turn",
        ylab = "Duration (sec.)")

2. ggplot2 绘图调整

通过scale_x_discrete指定x轴分类顺序:

library(ggplot2)
ggplot(well, aes(x = Pos_in_turn, y = d)) + 
  geom_boxplot(notch = TRUE) +
  scale_x_discrete(limits = as.character(1:10)) +
  labs(title = "How long does it take to say 'well'?\n(in 10-word turns from BNC-C)",
       x = "Position in turn",
       y = "Duration (sec.)")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:36:05