Alex M
Alex M

Reputation: 51

Having trouble aligning histogram and density plots in ggplot2 with cowplot

Only the stripped down density plot appears in the output:

library(ggplot2)
library(cowplot)

raises <- attitude$raises
df <- data.frame(raises)

ph <- ggplot(df, aes(x = raises)) +
  geom_histogram(binwidth = 1, color = "black", fill = "light grey") +
  scale_x_continuous(breaks = seq(40, 90, by = 10)) +
  ylim(0,3) +
  theme_classic()

pd <- ggplot(df, aes(x = raises)) +
  geom_density() +
  scale_x_continuous(breaks = seq(40, 90, by = 10)) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.1)), position = "right") +
  theme_classic() +
  theme(axis.line.x = element_blank(),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

alpl <- align_plots(ph, pd, align = "hv", axis = "tblr")
ggdraw(alpl[[1]]) + draw_plot(alpl[[2]])

enter image description here

I would like to overlay them so that you can see the histogram with the frequency as well as the density.

Upvotes: 0

Views: 129

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174338

You have an opaque plot background and panel background in your density plot which you need to remove in theme. Obviously, I don't have your data, but the following code gives you the idea:

library(ggplot2)
library(cowplot)

set.seed(1)

df <- data.frame(raises = c(rnorm(100, 65, 10)))

ph <- ggplot(df, aes(x = raises)) +
  geom_histogram(binwidth = 1, color = "black", fill = "light grey") +
  scale_x_continuous(breaks = seq(40, 90, by = 10), limits = c(40, 90)) +
  ylim(0,3) +
  theme_classic()

pd <- ggplot(df, aes(x = raises)) +
  geom_density() +
  scale_x_continuous(breaks = seq(40, 90, by = 10), limits = c(40, 90)) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.1)), position = "right") +
  theme_classic() +
  theme(axis.line.x = element_blank(),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        plot.background = element_blank(),
        panel.background = element_blank())

alpl <- align_plots(ph, pd, align = "hv", axis = "tblr")
ggdraw(alpl[[1]]) + draw_plot(alpl[[2]])

enter image description here

Upvotes: 1

Related Questions