简体   繁体   English

如何防止 geom_text 重叠标签?

[英]How can I prevent geom_text from overlapping labels?

I'm using geom_text from ggplot to annotate each of my plots in a facet_wrap .我正在使用geom_text中的facet_wrapggplot中注释我的每个图。 My code is shown below.我的代码如下所示。 num_zeros_text is just a dataframe with a single column, label , with a number in each row. num_zeros_text只是一个 dataframe 单列label ,每行都有一个数字。 I'm trying to follow the answer posted by Kamil Slowikowski in this post.我正在尝试遵循 Kamil Slowikowski 在这篇文章中发布的答案。 For some reason, my labels are ending up "overlapping" each other (see picture below), where essentially all numbers from the dataframe num_zeros_text are being displayed on each plot (I believe).出于某种原因,我的标签最终彼此“重叠”(见下图),基本上来自 dataframe num_zeros_text的所有数字都显示在每个 plot 上(我相信)。 I can't figure out why.我不知道为什么。

  ggplot(normalized_counts_subsampled, aes(value)) +
    geom_histogram() +
    facet_wrap(~bins, 100) +
    geom_text(data = num_zeros_text,
              aes(x = 0.75, y=50, label=label))

在此处输入图像描述

The issue is that you labels dataset does not contain the facetting variable.问题是您的标签数据集不包含构面变量。 Hence, how should ggplot2 know that you want only one number per facet and in which order?因此, ggplot2应该如何知道每个方面只需要一个数字以及按什么顺序? As a consequence all numbers are plotted in each facet.因此,所有数字都绘制在每个方面。

Here is a minimal reproducible example of your issue based on iris :这是基于iris的问题的最小可重现示例:

library(ggplot2)

num_zeros_text <- data.frame(
  label = c(1, 2, 3)
)

ggplot(iris, aes(Sepal.Length)) +
  geom_histogram() +
  facet_wrap(~Species) +
  geom_text(data = num_zeros_text,
            aes(x = 0.75, y=50, label=label))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

To fix your issue add a second column with the facetting variable to your labels dataset, ie for my reprex a Species column:要解决您的问题,请向您的标签数据集添加带有 facetting 变量的第二列,即对于我的代表Species列:

num_zeros_text$Species <- unique(iris$Species)

ggplot(iris, aes(Sepal.Length)) +
  geom_histogram() +
  facet_wrap(~Species) +
  geom_text(data = num_zeros_text,
            aes(x = 0.75, y=50, label=label))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM