星期二, 六月 19, 2012

ggplot的图形组合与添加jpeg文档的方法


最近有位朋友问了一个关于ggplot2作图的问题。涉及到多个图形组合的问题,所以还是费了一些时间来解决,自己也从中学习了一些新东西。顺手将这个画图的过程扔上来当作一篇博文吧。下图就是最后的结果。画这个图有几个障碍,一个是二维散点的置信椭圆,另一个是一维直方图的边缘显示。解决的方法是用ellipse包来生成置信椭圆数据,并且用gridExtra包来组合多个图形,还要用opts来去除图例标注的显示。
# 读入数据和加载包
data <-read.csv('d:\\data.csv',T)
library(ggplot2)
library(ellipse)
library(gridExtra)
library(plyr)
library(ReadImages)
 
#建立一个函数以生成置信椭圆
generatfun <- function(x) {
    as.data.frame(with(data,ellipse(cor(a,b),scale=c(sd(a),sd(b)),
             level=x,centre=c(mean(a),mean(b)))))}
# 根据不同的置信度来生成多个数据框并整合
i <-  seq(0.1,0.9,by=0.1)
data2 <- adply(i,1,generatfun)
names(data2) <- c('level','x','y')
 
# 绘制主图散点图,并将图例去除,这里point层和path层使用了不同的数据集
scatter <- ggplot() + 
    geom_point(data=data,aes(a,b,shape=type))+
    geom_path(data=data2,aes(x,y,group=level))+
    opts(legend.position = "none")+
    geom_vline(xintercept = mean(data$a),linetype=2)+
    geom_hline(yintercept = mean(data$b),linetype=2)
# 绘制上边的直方图,并将各种标注去除
hist_top <- ggplot()+geom_histogram(aes(data$a),colour='black',fill='gray',binwidth = 0.3)+
    opts(panel.background=theme_blank(),
         axis.title.x=theme_blank(), 
         axis.title.y=theme_blank(),
         axis.text.x=theme_blank(),
         axis.text.y=theme_blank(),
         axis.ticks=theme_blank())
# 同样绘制右边的直方图
hist_right <- ggplot()+geom_histogram(aes(data$b),colour='black',fill='gray',binwidth = 0.1)+
    opts(panel.background=theme_blank(),
         axis.title.x=theme_blank(), 
         axis.title.y=theme_blank(),
         axis.text.x=theme_blank(),
         axis.text.y=theme_blank(),
         axis.ticks=theme_blank())+
         coord_flip()
# 要由四个图形组合而成,可以用空白图作为右上角的图形也可以,但为了好玩加上了R的logo,这是一种在ggplot中增加jpeg位图的方法
logo <-  read.jpeg("d:\\Rlogo.jpg")
empty <- ggplot(data.frame(x=1:10,y=1:10),aes(x,y))+
    annotation_raster(logo,-Inf, Inf, -Inf, Inf)+
    opts(axis.title.x=theme_blank(), 
         axis.title.y=theme_blank(),
         axis.text.x=theme_blank(),
         axis.text.y=theme_blank(),
         axis.ticks=theme_blank())
# 最终的组合
grid.arrange(hist_top, empty, scatter, hist_right, ncol=2, nrow=2, widths=c(4,1), heights=c(1,4))
参考资料:
http://stackoverflow.com/questions/2397097/how-can-a-data-ellipse-be-superimposed-on-a-ggplot2-scatterplot
http://stackoverflow.com/questions/8545035/scatterplot-with-marginal-histograms-in-ggplot2

没有评论:

发表评论