首页 > 解决方案 > 如何使用ggplot2将我的图例水平而不是垂直?

问题描述

我很难理解为什么legend.horizontal不旋转我的图例轴所以它不垂直显示?任何帮助将不胜感激。

library(phyloseq)
library(ggplot2)

##phylum level 
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", )

垂直显示的绘图 + 图例示例

标签: rggplot2phyloseq

解决方案


离散值的图例本身并没有正式的方向,但其位置ggplot2决定了它最适合您的数据。这就是为什么这样的事情legend.direction在这里不起作用的原因。我没有phyloseq包或访问您的特定数据,所以我将向您展示它是如何工作的,以及您如何使用可重现的示例数据集来处理图例。

library(ggplot2)

set.seed(8675309)
df <- data.frame(x=LETTERS[1:8], y=sample(1:100, 8))

p <- ggplot(df, aes(x, y, fill=x)) + geom_col()
p

在此处输入图像描述

默认情况下,ggplot 将我们的图例放在右侧,并将其垂直组织为一列。当我们将图例移到底部时会发生以下情况:

p + theme(legend.position="bottom")

在此处输入图像描述

现在 ggplot 认为最好将该图例放入 4 列,每列 2 行。正如 u/Tech Commodities 提到的,您可以使用这些guides()函数来指定图例的外观。在这种情况下,我们将指定 2 列而不是 4 列。我们只需要提供列(或行)的数量,其余的由 ggplot 计算。

p + theme(legend.position="bottom") +
  guides(fill=guide_legend(ncol=2))

在此处输入图像描述

因此,要获得“水平排列”的图例,您只需指定应该只有一行:

p + theme(legend.position="bottom") +
  guides(fill=guide_legend(nrow=1))

在此处输入图像描述


推荐阅读