R中的边缘箱线图的直方图

时间:2013-04-18 12:41:53

标签: r histogram boxplot

如何使直方图中的X轴与边缘箱图匹配?

data <- rnorm(1000)
nf <- layout(mat = matrix(c(1,2),2,1, byrow=TRUE),  height = c(1,3))
layout.show(nf)
par(mar=c(5.1, 4.1, 1.1, 2.1))
boxplot(data, horizontal=TRUE,  outline=FALSE)
hist(data)

2 个答案:

答案 0 :(得分:11)

一种解决方案是将ylim=中的boxplot()设置为与xlim=中的hist()相同的范围。

set.seed(123)
data <- rnorm(1000)
nf <- layout(mat = matrix(c(1,2),2,1, byrow=TRUE),  height = c(1,3))
par(mar=c(5.1, 4.1, 1.1, 2.1))
boxplot(data, horizontal=TRUE,  outline=FALSE,ylim=c(-4,4))
hist(data,xlim=c(-4,4))

enter image description here

答案 1 :(得分:0)

使用 ggplot 网格包。

library(gridExtra)
library(ggplot2)
library(grid)

p1 = ggplot(aes(x = mpg), data = mtcars) +
  geom_histogram(fill = "lightblue", color = "black",binwidth = 1) +
  scale_x_continuous(limits = c((min(mtcars$mpg)),(max(mtcars$mpg))), 
                     breaks = pretty(mtcars$mpg, n = 10)) +
  labs(x = "", y = "Count", title = ("Histogram & Boxplot of mpg"))

p2 = ggplot(aes(x = "", y = mpg), data = mtcars) +
  stat_boxplot(geom ='errorbar', width = 0.4) +
  geom_boxplot(outlier.colour = "red") +
  coord_flip() +
  scale_y_continuous(limits = c((min(mtcars$mpg)),(max(mtcars$mpg))), 
                     breaks = pretty(mtcars$mpg, n = 10))  +
  stat_summary(fun.y = mean, colour = "purple", geom = "point", 
               shape = 18, size = 3) +
  labs(x = "", y = "mpg")


grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "first"))