我有一个数据框,其中包含以下因素:
rss<-c("rs","total","rs","total","total","total","rs","rs")
css<-c("G","S","S","Q","Q","Q","G","G")
batch<-c("5","6","6","7","7","8","7","5")
dat<-data.frame(rss,css,batch)
我想为每列绘制上述数据帧的数值矩阵,即按列将8 * 3矩阵转换为3,4 * 2子矩阵。这样我就可以遍历并绘制子矩阵数据。
newdat<-data.matrix(dat)
split.dat<-split(newdat,col(newdat))
par(mfrow=c(1,3))
for(i in split.dat){image(array(i,c(4,2)))}
有没有更好的方法来做同样的事情?也欢迎任何关于绘制image
答案 0 :(得分:2)
以下是其他一些选项,不过你的方式很好。
apply(newdat, 2, function(i) image(matrix(i, 4, 2)))
或者,使用raster
代替
library(raster)
par(mfrow=c(1,3))
apply(newdat, 2, function(i) plot(raster(matrix(i, 4, 2))) # plot as raster
# or
apply(newdat, 2, function(i) plot(raster(matrix(i, 4, 2)), useRaster=FALSE))
# pictured below, uses image()
或使用persp
nr <- 4
nc <- 2
par(mfrow=c(1,3))
apply(newdat, 2, function(i)
persp(0:nc, 0:nr, matrix(1, (nc+1), (nr+1)), zlim=c(0,2), phi=270,
box=FALSE, col = t(matrix(i, 4, 2))))
# the color matrix here is using the integers to define colors, but you may want to adjust that.
来自levelplot
的{{1}}:
lattice
答案 1 :(得分:2)
我认为这解决了ggplot2的问题。但是,您的数据格式很奇怪,并且不清楚为什么要按照您描述的方式绘制数据。在我看来,有一些变量缺失,特别是与我创建的row
数据框中的col
和newdat
相对应的变量。我建议你阅读Hadley Wickham的tidy data paper。
require(tidyr)
require(dplyr)
require(ggplot2)
rss<-c("rs","total","rs","total","total","total","rs","rs")
css<-c("G","S","S","Q","Q","Q","G","G")
batch<-c("5","6","6","7","7","8","7","5")
dat<-data.frame(rss,css,batch)
# convert into tidy data frame
dat %>% mutate(col=c(rep(1,4), rep(2,4)), row=c(1:4, 1:4)) %>%
gather(key, value, rss:batch) -> newdat
# plot
ggplot(newdat, aes(x=col, y=row, fill=value)) +
geom_tile() +
facet_wrap(~key) +
scale_x_discrete(breaks=c(1,2), limits=c(1,2)) +
theme_bw()
结果: