2

I want a boxplot to be overlayed on histogram. to avoid missing with the histogram, I am forced to draw the boxplot like that:

library(ggplot2)
ggplot(iris) + geom_boxplot(aes(x = Sepal.Length, y = factor(0)))

the plot with problimatic configuartion

However the plot doesn't appear right unless I swap between the x and y. correct plot, but not the needed configuration

I want to integrate a histogram with boxplot on the same coordinate, but it seems there is no way to plot a boxplot flipped without using coord_flip() that doesn't help here as it flip the whole plot.

ggplot(iris) +
  geom_histogram(aes(x = Sepal.Length))+
  geom_boxplot(aes(x = Sepal.Length, y = factor(0))) + 
  coord_flip()
Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
Omar113
  • 210
  • 1
  • 7

2 Answers2

4

Something like this?

library(ggplot2)
library(ggstance)

ggplot(iris, aes(x = Sepal.Length)) +
  geom_histogram() +
  geom_boxploth(aes(y = 3), width = 3, color = "blue", lwd = 2, alpha = .5) +
  theme_minimal()

enter image description here

Iaroslav Domin
  • 2,698
  • 10
  • 19
4

This works in the current development version of ggplot2, hopefully to be released soon.

library(ggplot2) # remotes::install_github("tidyverse/ggplot2")
packageVersion("ggplot2")
#> [1] '3.2.1.9000'

ggplot(iris) +
  geom_histogram(aes(x = Sepal.Length))+
  geom_boxplot(aes(x = Sepal.Length, y = factor(0)))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2019-11-12 by the reprex package (v0.3.0)

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104