如何使用 ggplot2 将我的图例水平而不是垂直?

How to turn my legend horizontal as opposed to vertical with 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", )

离散值的图例本身并没有正式的方向,但是 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))