r - 如何使用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))
推荐阅读
- pdf - 使 wkhtmltopdf 呈现文本而不是曲线
- c# - 如何通过确认从 Kendo Grid 中删除一行并将所选 ID 传递给 Destroy 方法
- debugging - 尝试在本地IIS vs2017下调试网站项目
- algorithm - 如何将二进制堆转换为二项式队列
- javascript - 饼图切片 - 质心
- uml - 序列图。演员可以OPT吗?
- javascript - 页面中另一个 SVG 的 Highcharts 阴影不适用于直线
- javascript - 获取数据后对设置状态做出反应
- r - 提取具有缺失值阈值的变量名称
- google-cloud-platform - 数据流:storage.Client() 导入错误或如何列出 GCP 存储桶的所有 blob