在R中的一个图上绘制18个图?

时间:2017-05-16 08:50:07

标签: r plot data-visualization

我有一个18列的数据框,我希望在一张图表上看到每个变量的季节性调整状态。

这是我的数据框的主管;

head(cityFootfall))

  Istanbul Eskisehir Mersin
1    44280     12452  11024
2    58713     13032  12773
3    21235      5629   5749
4    20934      5968   5764
5    21667      6022   5752
6    21386      6281   5920
Ankara Bursa Adana Izmir
1  19073  5098  8256 15623
2  22812  7551 10631 18511
3   8777  2260  3733  8625
4   8798  2252  3536  8573
5   8893  2398  3641  9713
6   8765  2391  3618 10542
Kayseri Antalya Konya
1    8450    2969  4492
2    8378    4421     0
3    3491    1744     0
4    3414    1833     0
5    3596    1733     0
6    3481    1785  1154
Samsun Kahramanmaras Aydin
1   4472          4382  4376
2   4996          4773  5561
3   1662          1865  2012
4   1775          1710  1957
5   1700          1704  1940
6   1876          1848  1437
Gaziantep Sanliurfa Izmit
1      3951      3752  3825
2      5412      4707  4125
3      2021      1326  1890
4      1960      1411  1918
5      1737      1204  1960
6      1833      1143  2047
Denizli Malatya
1    2742    3809
2    3658    4346
3    1227    1975
4    1172    1884
5    1102    2073
6    1171    2060
  

这是我的功能:

plot_seasonality=function(x){

par(mfrow=c(6,3)) 
plot_draw=lapply(x, function(x)  plot(decompose(ts(x,freq=7),type="additive")$x-decompose(ts(x,freq=7),type="additive")$seasonal)

}
plot_seasonality(cityFootfall)

当我运行此功能时,我收到错误消息:Error in plot.new() : figure margins too large但是当我将我的代码从par(mfrow=c(6,3)更改为par(mfrow=c(3,3)时,它的作品会给我最后9列图,如此图像{{ 3}}但我希望在单个图表中看到所有变量

有人可以帮我解决问题吗?

2 个答案:

答案 0 :(得分:1)

Fundamentally your windows is not big enough to plot that:

1) open a big window with dev.new(), or from Rstudio X11() under linux or quartz() under MacOSX)

2) simplify your ylab that will free space

# made up data
x <- seq(0,14,length.out=14*10)
y <- matrix(rnorm(14*10*6*3),nrow=3*6)

# large window (may use `X11()` on linux/Rstudio to force opening of new window)
dev.new(width=20,height=15)
par(mfrow=c(6,3))

# I know you could do that with `lapply` but don't listen to the fatwas 
# on `for` loops it often does exactly the job you need in R
for(i in 1:dim(y)[1]){
    plot(x,y[i,],xlab="Time",ylab=paste("variable",i),type="l")
}

You should also consider plotting several variables in the same graph (using lines after an initial plot).

All 18 graphs together

答案 1 :(得分:1)

根据建议:使用包tidyr以长格式转换数据,请参阅函数gather

我添加了一个时间变量,因为它丢失了。

temp <- cityFootfall %>% transform(time = 1:nrow(temp)) %>% gather(variable, key, -time) 

现在用ggplot2绘制它(默认设置,您可以按照自己的意愿调整)

gplot(temp, aes(x = time, y = key, group = variable, color = variable)) + geom_point() + geom_line()

enter image description here