繁体   English   中英

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

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

只有精简后的密度 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]])

在此处输入图像描述

我想叠加它们,这样你就可以看到频率和密度的直方图。

您的密度 plot 中有不透明的 plot 背景和面板背景,您需要在theme中将其删除。 显然,我没有你的数据,但下面的代码给了你这个想法:

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