如何在ggplot2中对分类气泡图按气泡大小降序排列?
解决ggplot2分类气泡图按气泡大小降序排列的问题
问题原因
你当前的代码仅对数据集整体按Mean_Abundance降序排列,但Legend_Taxa是因子类型,ggplot默认遵循因子的原始水平顺序渲染y轴,不会随数据框行顺序自动改变,因此无法实现按气泡大小排序的效果。
解决方案
要让y轴分类按对应气泡的大小降序排列,需要重新指定Legend_Taxa的因子水平顺序,以每个分类的代表丰度(最大/平均)作为排序依据:
完整代码示例
library(dplyr) library(ggplot2) # 计算每个分类的最大丰度,按该值降序提取分类顺序 taxa_order <- test1 %>% group_by(Legend_Taxa) %>% summarise(max_abund = max(Mean_Abundance)) %>% arrange(desc(max_abund)) %>% pull(Legend_Taxa) # 将Legend_Taxa转换为指定顺序的因子 test2 <- test1 %>% mutate(Legend_Taxa = factor(Legend_Taxa, levels = taxa_order)) # 绘制气泡图 p <- ggplot(test2, aes(x = Group, y = Legend_Taxa, size = Mean_Abundance)) + geom_point(alpha = 0.5) + scale_size(range = c(.1, 24), name = "Mean Abundance") print(p)
可选调整
- 若想按分类的平均丰度排序,将
summarise(max_abund = max(Mean_Abundance))替换为summarise(mean_abund = mean(Mean_Abundance))即可 - 因子水平设置完成后,y轴会自动从顶部到底部对应丰度从高到低排列,气泡大小的视觉层级与分类顺序匹配
内容的提问来源于stack exchange,提问作者DS14
相关产品推荐
相关产品推荐

