I'm using geom_text
from ggplot
to annotate each of my plots in a facet_wrap
. My code is shown below. num_zeros_text
is just a dataframe with a single column, label
, with a number in each row. I'm trying to follow the answer posted by Kamil Slowikowski in
CodePudding user response:
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? As a consequence all numbers are plotted in each facet.
Here is a minimal reproducible example of your issue based on 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, i.e. for my reprex a Species
column:
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`.