我想在一张画布上绘制 3 个直方图:
x <- rnorm(100)
y <- rnorm(100, 1, 2)
z <- rnorm(100, 2, 3)
par(mfrow=c(3, 1))
sapply(list(x, y, z), hist)
我得到的只是一个直方图z
。是否可以使用 来做到这一点sapply
?
我会ggplot2
用来创建多个直方图。优点是ggplot2
将多个图视为一个带有子图的大图,保持 x 轴和 y 轴相等(正常hist
情况下不会这样做)。
在代码中:
library(ggplot2)
library(reshape2) # ...for melt
dat = data.frame(x, y, z) # Put into one big data.frame
dat_melt = melt(dat) # Change structure of the data a bit
ggplot(dat_melt, aes(x = value)) + geom_histogram() + facet_wrap(~ variable)