R studio:在直方图中制作小图,并使用par函数重复它我需要的次数

时间:2017-01-29 05:42:32

标签: r plot subplot insets

我需要为我的变量做一个直方图,即“旅行时间”。在其中,我需要绘制回归(相关)数据,即我的观察数据与预测数据。我需要在一天和一周的不同时间重复它(简单来说,使用par函数制作这样的数字矩阵)。现在,我可以绘制直方图并以矩阵形式排列,但我在内部绘图中遇到问题(将x和y数据与y = x线一起绘制,并将它们排列在连续的直方图中,在矩阵中)。我怎么能这样做,如下图所示。任何帮助,将不胜感激。谢谢!

enter image description here

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是循环遍历数据,并在每次迭代时创建所需的绘图。这是一个不太精确的例子,但它显示了如何在较大的情节上绘制小图的逻辑。您将不得不调整代码以使其以您需要的方式工作,但它不应该那么困难。

# create some sample dataset (your x values)
a <- c(rnorm(100,0,1))
b <- c(rnorm(100,2,1))
# create their "y" values counterparts
x <- a + 3
y <- b + 4
# bind the data into two dataframes (explanatory variables in one, explained in the other)
data1 <- cbind(a,b)
data2 <- cbind(x,y)

# set dimensions of the plot matrix
par(mfrow = c(2,1))
# for each of the explanatory - explained pair
for (i in 1:ncol(data2))
{
        # set positioning of the histogram
        par("plt" = c(0.1,0.95,0.15,0.9))
        # plot the histogram
        hist(data1[, i])
        # set positioning of the small plot
        par("plt" = c(0.7, 0.95, 0.7, 0.95))
        # plot the small plot over the histogram
        par(new = TRUE)
        plot(data1[, i], data2[, i])
        # add some line into the small plot
        lines(data1[, i], data1[, i])
}