使用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
相关产品推荐
相关产品推荐

