使用ggplot2绘图时如何将垂直排列的图例改为横向排列?
你设置的legend.direction未生效是因为fantaxtic_bar函数生成的ggplot对象默认给图例设置了固定的垂直引导参数,优先级高于theme中的全局设置,需要额外通过guides函数指定图例的排列规则,修改后的代码如下:
library(phyloseq) library(ggplot2) ## 门水平分类统计 ps_tmp <- get_top_taxa(physeq_obj = ps.phyl, n = 10, relative = TRUE, discard_other = FALSE, other_label = "Other") ps_tmp <- name_taxa(ps_tmp, label = "Unkown", species = T, other_label = "Other") phyl <- fantaxtic_bar(ps_tmp, color_by = "phylum", label_by = "phylum",facet_by = "TREATMENT", other_label = "Other", order_alg = "as.is") # 修改后的绘图代码 phyl + theme( legend.direction = "horizontal", legend.position = "bottom" ) + # 强制fill映射的图例排成1行,实现水平布局 guides(fill = guide_legend(nrow = 1, byrow = TRUE))
补充说明:
- 如果你使用的
fantaxtic_bar版本是用color而不是fill映射分类颜色,把guides中的fill替换为color即可 - 如需调整图例项间距、文字角度,可以在
theme中追加legend.spacing.x = unit(0.5, 'cm')、legend.text = element_text(angle = 0)这类参数自定义样式
你当前生成的垂直图例效果参考:
内容的提问来源于stack exchange,提问作者Onco_rhynchus
相关产品推荐
相关产品推荐

