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

R语言分面哑铃图y轴刻度值按指定顺序排列的实现问题

解决方法

你当前代码中conditon2因子的排序逻辑为按EndpointError前后测差值降序排列,不符合自定义分组排序要求,仅需要替换原代码中conditon2的因子水平设置逻辑即可,完整可运行代码如下:

library(tidyverse)
library(ggplot2) 
library(rlang)
library(utils)
library(data.table)
library(dumbbell)

# 定义自定义排序规则:先按分组后缀优先级排序,同一分组内按前缀CEN>IPS>CTL排序
data10 <- data10 %>%
  mutate(
    # 提取conditon2的分组后缀(RRR/LLL/RLR/LRL)
    group_suffix = str_extract(conditon2, "([A-Z]{3})$"),
    # 提取conditon2的前缀(CEN/IPS/CTL)
    group_prefix = str_extract(conditon2, "^([A-Z]{3})"),
    # 前缀排序权重:CEN排最前,其次IPS,最后CTL
    prefix_order = case_when(
      group_prefix == "CEN" ~ 1,
      group_prefix == "IPS" ~ 2,
      group_prefix == "CTL" ~ 3
    ),
    # 后缀排序权重,匹配两个分面的展示要求
    suffix_order = case_when(
      group_suffix == "RRR" ~ 1, # Retention分面要求RRR排最前
      group_suffix == "LLL" ~ 2,
      group_suffix == "RLR" ~ 3, # Transfer分面要求RLR紧随LLL
      group_suffix == "LRL" ~ 4
    )
  ) %>%
  # 按权重排序后提取conditon2的顺序作为因子水平
  arrange(suffix_order, prefix_order)

# 给conditon2设置自定义排序的因子水平
data10$conditon2 <- factor(data10$conditon2, levels = unique(data10$conditon2))

# 后续绘图逻辑
data10A<-data10 %>% select(conditon2,Trial_type,EndpointError_102,EndpointError_104) %>% mutate("key"="Change In Endpoint Error (cm)")

data10A$Trial_type <- factor(data10A$Trial_type, levels = 1:2, labels = c("Retention", "Transfer"))

dumbbell::dumbbell(data10A, id="conditon2", key="Trial_type", leg = "Test time", column1 = "EndpointError_102", column2="EndpointError_104", delt=1, lab1="Pretest", lab2="Posttest", p_col1 = "black", p_col2 = "grey40", textsize = 4, segsize = 1.5, pointsize = 2.5, title = "Change in Endpoint error (cm)")  + 
  xlim(0.7,3.0) + facet_wrap( Trial_type ~., scales="free_y", ncol=1) +
  theme(axis.text.x = element_text(size = 12,face="bold"),
        axis.text.y = element_text(size = 11, face = "bold")) + 
  theme(legend.position="right") + 
  theme(legend.text=element_text(size=12), legend.title=element_text(size=14)) + 
  theme(strip.text = element_text(face="bold", size=14, color = "black"))

关键调整说明

  • 自定义排序权重完全匹配你的展示要求:Retention分面下RRR分组排在最前,之后是LLL分组;Transfer分面下RLR分组紧随LLL分组展示
  • 同一分组下的CEN/IPS/CTL指标保持固定顺序,方便跨分组对照
  • 把facet_wrap的scales参数调整为free_y,仅放开y轴的自由适配,x轴保持统一范围更方便对比误差值差异

内容的提问来源于stack exchange,提问作者Reuben Newton Addison

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:36:02