Consider this code
ggplot(mpg, aes(x = displ)) +
geom_histogram(aes(y = after_stat(density)),
color = 'lightblue', size = .8)+
geom_freqpoly(aes(y = after_stat(density)),
color = 'red', size = .8)
I want to add points on the top of each bar, however using this
ggplot(mpg, aes(x = displ)) +
geom_histogram(aes(y = after_stat(density)),
color = 'lightblue', size = .8)+
geom_freqpoly(aes(y = after_stat(density)),
color = 'red', size = .8)+
geom_point(aes(y = after_stat(density)))
produces the following error
Error in `geom_point()`:
! Problem while mapping stat to aesthetics.
ℹ Error occurred in the 3rd layer.
Caused by error in `map_statistic()`:
! Aesthetics must be valid computed stats.
✖ The following aesthetics are invalid:
✖ `y = after_stat(density)`
ℹ Did you map your stat in the wrong layer?
I would like to add the point adding only geom_point()
is it possible?
Consider this code
ggplot(mpg, aes(x = displ)) +
geom_histogram(aes(y = after_stat(density)),
color = 'lightblue', size = .8)+
geom_freqpoly(aes(y = after_stat(density)),
color = 'red', size = .8)
I want to add points on the top of each bar, however using this
ggplot(mpg, aes(x = displ)) +
geom_histogram(aes(y = after_stat(density)),
color = 'lightblue', size = .8)+
geom_freqpoly(aes(y = after_stat(density)),
color = 'red', size = .8)+
geom_point(aes(y = after_stat(density)))
produces the following error
Error in `geom_point()`:
! Problem while mapping stat to aesthetics.
ℹ Error occurred in the 3rd layer.
Caused by error in `map_statistic()`:
! Aesthetics must be valid computed stats.
✖ The following aesthetics are invalid:
✖ `y = after_stat(density)`
ℹ Did you map your stat in the wrong layer?
I would like to add the point adding only geom_point()
is it possible?
2 Answers
Reset to default 1Use
ggplot(mpg, aes(x = displ)) +
geom_histogram(aes(y = after_stat(density)),color = 'lightblue', size = .8)+
geom_freqpoly(aes(y = after_stat(density)),color = 'red', size = .8)+
geom_point(aes(y = after_stat(density)), stat = "bin")
If you look at the help pages for ?geom_histogram
and ?geom_freqpoly
you'll see they have default stat="bin"
while ?geom_point
has the default stat="identity"
. You need to use the right stat=
parameter that provides the correct after_stat
you are trying to use in that layer.
We can use stat_bin
:
library(ggplot2)
ggplot(mpg, aes(x = displ, y = after_stat(density))) +
geom_histogram(color = 'lightblue', size = .8)+
geom_freqpoly(color = 'red', size = .8) +
stat_bin(geom = "point")