ScatterPlot和一个直方图一起绘制

时间:2014-04-06 19:42:09

标签: r

我想用右侧的'散点图'和直方图来显示时间序列数据,但我还没弄清楚如何关闭上方的直方图。

代码示例:

install.packages("psych")
library(psych)
data = matrix(rnorm(n=100000,mean=2,sd=1.5), nrow = 100, ncol=1000)
fs = list()
fs$p_Z = 1*(data>2)
n_p = 1;
  for(i in floor(seq(1,dim(data)[2],length.out=n_p)))
{
  scatter.hist(x = rep(1:length(data[,i])), y = data[,i],
               xlab = 'observations',
               ylab = 'log(TPM)',
               title = 'Mixture Plot',
               col = c("red","blue")[fs$p_Z[,i]+1], 
               correl = FALSE, ellipse = FALSE, smooth = FALSE)
}

结果:

scatter plot with two histograms, one upper side and one on right side

预期成果: 与我的相同,但在上侧没有直方图。即,只有右侧的直方图(TPM)。

注意:我使用psych package, scatter.hist function这似乎很容易使用,但无法找到如何关闭一个直方图。

1 个答案:

答案 0 :(得分:3)

在灵活性结束的地方,黑客行为开始了。如果你看一下scatter.hist函数,你会发现它是R基本图形的基本用法。修改后的代码将创建您想要的图:

scat.hist <- function(x, y, xlab = NULL, ylab = NULL, title = "", ...) {

## Create layout
layout(matrix(c(1,2),1,2,byrow=TRUE), c(3,1), c(1,3))

## Plot scatter
par(mar=c(5,5,3,1))
plot(x= x, y = y, xlab = xlab, ylab = ylab, main = title, ...)

## Right histogram
yhist <- hist(y, plot = FALSE, breaks = 11)
par(mar=c(5,2,3,1))
mp <- barplot(yhist$density, space=0, horiz=TRUE, axes = FALSE)
## Density
d <- density(y, na.rm = TRUE, bw = "nrd", adjust = 1.2)
temp <- d$y
        d$y <- (mp[length(mp)] - mp[1] + 1) * (d$x - min(yhist$breaks))/(max(yhist$breaks) - min(yhist$breaks))
        d$x <- temp
lines(d)
}

让我们尝试第一行:

i = 1
scat.hist(x = seq_along(data[,i]), y = data[,i], col = c("red", "blue")[fs$p_Z[,i]+1], xlab = 'observations', ylab = 'log(TPM)', title = 'Mixture Plot')

enter image description here