Closed
Description
In an attempt to create a bar plot while binning data, I have stumbled across a surprising interaction between geom_col()
and geom_text()
.
The following code is supposed to do two things:
- Create bars with
geom_col()
by calculatingdata
on my own - Annotate the bars with
geom_text()
by usingstat_bin()
to calculate the data
faithful |>
ggplot2::ggplot(ggplot2::aes(x = eruptions)) +
ggplot2::geom_col(
data = function(x) {
bins <- ggplot2:::bin_breaks_bins(
x_range = range(faithful$eruptions),
bins = 30,
center = NULL,
boundary = 4,
closed = "right"
)
h <- hist(
faithful$eruptions,
plot = FALSE,
breaks = bins$breaks
)
data.frame(mids = h$mids, count = h$counts)
# Alternatively, return ggplot2:::bin_vector(x = faithful$eruptions, bins = bins)
# and map x = xmin + width/2
},
mapping = ggplot2::aes(
x = mids,
y = count
),
inherit.aes = FALSE
) +
ggplot2::geom_text(
mapping = ggplot2::aes(
y = ggplot2::after_stat(count),
label = ggplot2::after_stat(count)
),
stat = "bin",
bins = 30,
binwidth = NULL,
center = NULL,
boundary = 4,
closed = "right"
)
However, this leads to suprising behavior in two regards:
- The numbers calculated by
stat_bin()
are off. - They become correct if the whole
geom_col()
is commented out.
Is this somehow correct behavior or a bug?
Using ggplot2 3.5.0 with R 4.3.3
(Why create the graph above like that in the first place? I deliberately want to avoid geom_histogram()
because the count bars are not supposed to touch each other, hence geom_col()
.)
Metadata
Metadata
Assignees
Labels
No labels