如何在R中创建具有公共X轴的多面板直方图

时间:2018-03-27 15:35:38

标签: r ggplot2

这是我的代码:



library(ggplot2)

ifile <- read.table("C:/files/text.lu", skip = 2, header = TRUE, sep="\t")
ifileVf2 <- data.frame(ifile["Vf2"], ifile["Site"])

quantiles <- quantile(ifileVf2$Vf2[ifileVf2$Site == '1'], c(0.001, 0.999))
Site_1_Values <- hist(ifileVf2$Vf2[(ifileVf2$Site == '1') & (ifileVf2$Vf2 > quantiles[1]) & (ifileVf2$Vf2 < quantiles[2])], breaks=150, freq=TRUE, right=TRUE)
quantiles <- quantile(ifileVf2$Vf2[ifileVf2$Site == '2'], c(0.001, 0.999))
Site_2_Values <- hist(ifileVf2$Vf2[(ifileVf2$Site == '2') & (ifileVf2$Vf2 > quantiles[1]) & (ifileVf2$Vf2 < quantiles[2])], breaks=150, freq=TRUE, right=TRUE)

par(mfrow=c(2,1))
plot( Site_1_Values, col=rgb(0,0,1,1/4),  panel.first = grid())
plot( Site_2_Values, col=rgb(0,1,0,1/4), add=T,  panel.first = grid())
&#13;
&#13;
&#13;

这是结果:

enter image description here 如何将两个直方图放入不同的面板但是常见的x轴?

1 个答案:

答案 0 :(得分:2)

library(ggplot2)

# example data
dat <- data.frame(
  voltage = c(rnorm(500, 0, 10), y = rnorm(500, 10, 10)),
  site = c(rep("site1", 500), rep("site2", 500))
)

# plot
ggplot(dat, aes(x = voltage, fill = site)) + 
  geom_histogram() + 
  facet_grid(site ~ .)

enter image description here