简体   繁体   English

无法将 ggplot2 中的直方图和密度图与 cowplot 对齐

[英]Having trouble aligning histogram and density plots in ggplot2 with cowplot

Only the stripped down density plot appears in the output:只有精简后的密度 plot 出现在 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]])

在此处输入图像描述

I would like to overlay them so that you can see the histogram with the frequency as well as the density.我想叠加它们,这样你就可以看到频率和密度的直方图。

You have an opaque plot background and panel background in your density plot which you need to remove in theme .您的密度 plot 中有不透明的 plot 背景和面板背景,您需要在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]])

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM