geom_boxplot 作为直方图中的插图
Posted
技术标签:
【中文标题】geom_boxplot 作为直方图中的插图【英文标题】:geom_boxplot as inset in histogram 【发布时间】:2022-01-17 17:04:25 【问题描述】:我想知道是否可以将分组箱线图作为 插图 绘制成带有密度线的(更大的)直方图:
玩具数据:
df <- structure(list(role = c("Recipient", "Speaker", "Recipient",
"Recipient", "Recipient", "Speaker", "Recipient", "Recipient",
"Speaker", "Speaker", "Recipient", "Speaker", "Recipient", "Recipient",
"Recipient", "Speaker", "Recipient", "Speaker", "Recipient",
"Speaker", "Recipient", "Recipient", "Speaker", "Recipient",
"Recipient", "Speaker", "Speaker", "Speaker", "Recipient", "Speaker",
"Speaker", "Recipient", "Speaker", "Recipient", "Recipient",
"Speaker", "Recipient", "Recipient", "Recipient", "Speaker",
"Speaker", "Recipient", "Speaker", "Recipient", "Speaker", "Recipient",
"Speaker", "Speaker", "Recipient", "Recipient", "Speaker", "Recipient",
"Recipient", "Speaker", "Recipient", "Recipient", "Recipient",
"Speaker", "Recipient", "Speaker", "Recipient", "Speaker", "Recipient",
"Recipient", "Speaker", "Recipient", "Recipient", "Speaker",
"Recipient", "Recipient", "Recipient", "Speaker", "Recipient",
"Speaker", "Recipient", "Speaker", "Recipient", "Recipient",
"Recipient", "Recipient", "Speaker", "Recipient", "Recipient",
"Recipient", "Speaker", "Recipient", "Speaker", "Recipient",
"Recipient", "Speaker", "Recipient", "Recipient", "Speaker",
"Recipient", "Recipient", "Recipient", "Speaker", "Recipient",
"Speaker", "Recipient"), increase_max = c(0.008, 0.118, NA, NA,
NA, 0.209, NA, 0.001, 0.111, NA, NA, NA, NA, NA, 0.007, 0.002,
0.006, 0.255, 0.009, NA, 0.004, 0.232, NA, 0.007, 0.004, 0.095,
0.09, NA, 0.002, NA, 0.05, NA, 0.02, 0.045, 0.002, NA, NA, 0.005,
0.012, NA, 0.037, NA, 0.066, NA, 0.019, 0.002, 0.136, NA, 0.003,
NA, 0.128, 0.004, 0.003, NA, NA, NA, 0.03, 0.042, NA, 0.138,
0.139, 0.126, 0.002, NA, 0.005, NA, 0.002, 0.01, 0.001, NA, 0.005,
0.003, NA, NA, 0.002, NA, 0.005, NA, NA, 0.015, 0.007, 0.021,
NA, NA, NA, NA, NA, 0.171, 0.02, 0.036, 0.026, 0.001, 0.033,
0.127, 0.339, 0.075, 0.037, 0.083, NA, 0.041)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -100L))
我可以像这样单独绘制两个图形(注意:直方图的数据是根据多个参数过滤的,箱线图的数据是未过滤的):
带密度线的直方图:
df %>%
filter(
!is.na(increase_max) &
increase_max >= 0.05 &
increase_max <= 0.5) %>%
ggplot(aes(x = increase_max)) +
geom_histogram(aes(y = after_stat(density), fill = role), binwidth = 0.05, position = "identity", alpha = 0.35) +
geom_density(aes(colour = role)) +
scale_colour_manual(aesthetics = c("fill", "colour"), values = c("blue", "red")
)
箱线图:
df %>%
ggplot(aes(y = increase_max, x = role)) +
geom_boxplot()
我正在寻找的输出将与此类似:
【问题讨论】:
【参考方案1】:您可以使用cowplot
轻松叠加和插入图。使用hp
作为直方图,bp
作为箱线图:
library(cowplot)
ggdraw() +
draw_plot(hp) +
draw_plot(bp, x = .5, y = .65, width = .35, height = .35)
【讨论】:
非常酷。谢谢!以上是关于geom_boxplot 作为直方图中的插图的主要内容,如果未能解决你的问题,请参考以下文章