【问题标题】:How to turn my legend horizontal as opposed to vertical with ggplot2?如何使用ggplot2将我的图例水平而不是垂直?
【发布时间】:2021-12-03 17:10:42
【问题描述】:

我很难理解为什么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", )

【问题讨论】:

  • 我不知道你正在使用的包,所以无法测试,但不是 legend.direction() 类似 '+ guides(fill = guide_legend(nrow = 1, byrow = TRUE) ) +' 可能会起作用

标签: r ggplot2 phyloseq


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多