**关于ggplot2包的画图**
首先关于用qplot快速绘制
如果你没有安装ggplot这个包的话,你的执行下面的命令
install.packages(“ggplot2”)
然后加载ggplot2包
library("ggplot2")
创建图的简单代码如下
foo <- c(1.1,2,3.5,3.9,4.2)
bar <- c(2,2.2,-1.3,0,0.2)
qplot(foo,bar)
运行结果如下
添加标题和轴标签
qplot(foo,bar,main="My lovely qplot",xlab="x axis label",ylab="location y")
运行结果如下
下面将使用Geoms设置外观
qplot(foo,bar,geom="blank") + geom_point() + geom_line()
qplot(foo,bar,geom="blank") + geom_point(size=3,shape=6,color="blue") +geom_line(color="red",linetype=2)
myqplot <- qplot(foo,bar,geom="blank") + geom_line(color="red",linetype=2) myqplot
myqplot + geom_point(size=3,shape=3,color="blue")
`myqplot + geom_point(size=3,shape=7,color=“blue”)
下面对一些数据做相应的处理
x <- 1:20
y <- c(-1.49,3.37,2.59,-2.78,-3.94,-0.92,6.43,8.51,3.41,-8.23,-12.01,-6.58,2.87,14.12,9.63,-4.58,-14.78,-11.67,1.17,15.62)
ptype <- rep(NA,length(x=x))
ptype
ptype[y>=5] <- "too_big"
ptype[y<=-5] <- "too_small"
ptype[(x>=5&x<=15)&(y>-5&y<5)] <- "sweet"
ptype[(x<5|x>15)&(y>-5&y<5)] <- "standard"
ptype <- factor(x=ptype)
ptype
结果如下
> x <- 1:20
> x <- 1:20
> y <- c(-1.49,3.37,2.59,-2.78,-3.94,-0.92,6.43,8.51,3.41,-8.23,-12.01,-6.58,2.87,14.12,9.63,-4.58,-14.78,-11.67,1.17,15.62)
> ptype <- rep(NA,length(x=x))
> ptype
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[19] NA NA
> ptype[y>=5] <- "too_big"
> ptype[y<=-5] <- "too_small"
> ptype[(x>=5&x<=15)&(y>-5&y<5)] <- "sweet"
> ptype[(x<5|x>15)&(y>-5&y<5)] <- "standard"
> ptype <- factor(x=ptype)
> ptype
[1] standard standard standard standard sweet
[6] sweet too_big too_big sweet too_small
[11] too_small too_small sweet too_big too_big
[16] standard too_small too_small standard too_big
Levels: standard sweet too_big too_small
qplot(x,y,color=ptype,shape=ptype)
结果如下
qplot(x,y,color=ptype,shape=ptype)
qplot(x,y,color=ptype,shape=ptype) + geom_point(size=4) +
geom_line(mapping=aes(group=1),color="black",lty=2) +
geom_hline(mapping=aes(yintercept=c(-5,5)),color="red") +
geom_segment(mapping=aes(x=5,y=-5,xend=5,yend=5),color="red",lty=3) +
geom_segment(mapping=aes(x=15,y=-5,xend=15,yend=5),color="red",lty=3)