簡體   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