Hi I want to create a similar chart as shown below with R script:
taken from: https://community.tableau.com/thread/194440
this is my code in R :
You're getting Error: stat_bin() must not be used with a y aesthetic.
because you can't specify y
in the aesthetic of a histogram. If you want to mix plots that have different parameters, you need to supply distinct aesthetics. I'll demonstrate with iris
like so:
ggplot(iris, aes(x = Sepal.Width)) +
geom_histogram(binwidth = 0.05) +
geom_boxplot(aes(x = 3, y = Sepal.Width))
Unfortunately, the default for boxplots is vertical, for histograms is horizontal, and coord_flip()
is all-or-nothing, so you're left with this awful thing:
Best I can figure out is instead of having them overlap, put one on top of the other with the gridExtra
package:
a <- ggplot(iris, aes(x = Sepal.Width)) +
geom_histogram(binwidth = 0.05)
b <- ggplot(iris, aes(x = "", y = Sepal.Width)) +
geom_boxplot() +
coord_flip()
grid.arrange(a,b,nrow=2)
which gives us something pretty good: