簡體   English   中英

R中的邊緣箱線圖的直方圖

[英]Histogram with marginal boxplot in R

如何使直方圖中的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)

一種解決方案是將ylim= boxplot()中的xlim=hist() xlim=相同的范圍。

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))

在此輸入圖像描述

使用ggplotgrid包。

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"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM