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

使用fct_reorder按中位数排序箱线图失效的解决方案

问题

尝试使用fct_reorder(或reorder)按中位数对箱线图进行排序,但输出的箱线图并未按中位数排序,两种方法均无效。当前代码如下:

box_scottishpolitics_karma <<- ggplot(hedges_scottishpolitics_data,
                                        aes(x=fct_reorder(unique_word, 
                                            utterance_score, median), 
    y=utterance_score)) + 
    geom_boxplot(fill="red", color = "black") +
    scale_y_continuous(trans=scales::pseudo_log_trans(base = 10)) +
    ggtitle("Subreddit: Scottish Politics") +
    xlab("Hedge/Booster") +
    ylab("Karma Score (log10)") +
    coord_flip() +
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
    geom_boxplot(data=boosters_scottishpolitics_data, fill="lightblue", 
                 color = "black") +
    coord_flip() +
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

当前输出的箱线图未按中位数排序。

解决方案

由于数据结构更新,数据集新增z-score字段,需同时生成对应箱线图。可通过以下步骤解决排序问题:

  • 合并两个数据集,添加type列标记hedge和booster;
  • 将type转为因子类型;
  • 创建两个按中位数排序的列,分别对应Karma Score和z-score;
  • 基于排序列绘制箱线图。

实现代码如下:

# 合并两个数据集
hedges_scottishpolitics_data <- hedges_scottishpolitics_data %>%
    mutate(type = "hedge")
boosters_scottishpolitics_data <<- boosters_scottishpolitics_data %>%
    mutate(type = "booster")
all_scottishpolitics_data <- rbind(hedges_scottishpolitics_data, boosters_scottishpolitics_data)

# 将'type'列转为因子类型(用于箱线图着色)
all_scottishpolitics_data$type <- as.factor(all_scottishpolitics_data$type)
all_scottishpolitics_data <- all_scottishpolitics_data %>%
    ungroup() %>%
    # 添加两个排序列:一个按Karma Score中位数排序,一个按z-score中位数排序
    mutate(word_med_order = fct_reorder(unique_word, utterance_score))%>%
    mutate(word_med_order_z = fct_reorder(unique_word, z_score))
  
# Karma Score箱线图,使用word_med_order按中位数排序
box_scottishpolitics_karma <- ggplot(all_scottishpolitics_data, aes(x = word_med_order, y = utterance_score, fill = type)) +
    geom_boxplot(color = "black") +
    scale_y_continuous(trans = scales::pseudo_log_trans(base = 10)) +
    ggtitle("Subreddit: r/scottishpolitics") +
    xlab("Hedge/Booster") +
    ylab("Karma Score (log10)") +
    coord_flip() +
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
  
# Z-score箱线图,使用word_med_order_z按中位数排序
box_scottishpolitics_z <- ggplot(all_scottishpolitics_data, aes(x = word_med_order_z, y = z_score, fill = type)) +
    geom_boxplot(color = "black") +
    scale_y_continuous(trans = scales::pseudo_log_trans(base = 10)) +
    ggtitle("Subreddit: r/scottishpolitics") +
    xlab("Hedge/Booster") +
    ylab("Z-Score (log10)") +
    coord_flip() +
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

最终可得到按中位数正确排序的Karma和Z-score箱线图。

内容的提问来源于Stack Exchange,提问作者Sikamixoticelixer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 19:44:54