如何在ggplot中将自定义boxplot添加到直方图

时间:2019-06-26 09:02:58

标签: r ggplot2 graph boxplot

我创建了一个直方图,并删除了boxplot.stat函数给定的上限和下限的异常值。然后使用cowplot,在直方图的顶部使用geom_boxplot添加了箱线图。但是,geom_boxplotboxplot.stat的所有统计信息均具有不同的值,因此我的箱线图显示了以下直方图中已删除的异常值。我试图通过插入boxplot.stats中的值来手动更改箱线图的值。

以下是可重现的示例:

set.seed(1)
Data <- data.table(
  "X" = sample(1:100),
  "Y" = sample(1:100))
)

numeric <-colnames(Data)

for (c in numeric){

  #Remove Outliers:
  stats <- boxplot.stats(Data[,get(c)])$stats
  upper.lim <- stats[5]
  median <- stats[3]
  lower.lim <- stats[1]


df2<-Data[!(get(c)>upper.lim | get(c)<lower.lim),] #filter to remove outliers

plotmain <- ggplot(df2, aes(x=df2[,get(c)])) +
  geom_histogram(colour="#102c59", fill="#5182d1", alpha=0.7) + 
  scale_x_continuous(labels = comma,breaks = scales::pretty_breaks(n = 10)) +
  scale_y_continuous(labels = comma) +
  ylab("Number of records") + 
  xlab(gsub("_", " ", c)) +
  ggtitle(title) + 
  theme_grey(base_size=8) 

xbox <- axis_canvas(plotmain, axis = "x", coord_flip = TRUE) + 
  geom_boxplot(data=df2,aes_string(x=c, ymin="lower.lim", lower=stats[2], middle="median", upper=stats[4], ymax="upper.lim"),stat="identity",
               outlier.shape=NA) + coord_flip() #add boxplot on top of histogram

p1 <- insert_xaxis_grob(plotmain, xbox, grid::unit(0.3, "in"), position = "top")
histbox <- ggdraw(p1) #join the two plots

g<-grid.arrange(histbox, tbl, layout_matrix=rbind(c(1),c(1),c(1),c(1),c(2)), nrow=4)
histbox <- ggdraw(p1)

ggsave(file="g.png",width=20, height=15, units="cm")

}

我得到的错误是:

Error: geom_boxplot requires the following missing aesthetics: x

我曾尝试在美学中插入x = 1和x =“”,但这给了我一个完全填充的黑匣子。

enter image description here

1enter image description here

0 个答案:

没有答案