如何用R画折线图,散点图,平滑曲线图
例子:
week |
1 |
2 |
3 |
4 |
5 |
6 |
x |
3 |
8 |
19 |
24 |
6 |
1 |
y |
1 |
25 |
21 |
3 |
2 |
1 |
要求是以week为横坐标,画出x-week,y-week的折线图,散点图及平滑曲线图。
一.散点图
## 输入数据 ##
> week<-c(1,2,3,4,5,6)
> x<-c(3,8,19,24,6,1)
> y<-c(1,25,21,3,2,1)
## 画x-week散点图 ##
> plot(week,x,col="red",pch=22,bg="yellow",xlim=c(0,6),ylim=c(0,30),lwd=2,xlab="WEEK",ylab="STUDENT",main="lesson",sub="class",col.main="green",font.main=2,asp=0,cex=1.2);
## 结果如下 ##
## 注释 ##
col 颜色
pch symbol 属性 1-25
xlim和ylim为坐标刻度范围
xlab和ylab为坐标标题
lwd line width for drawing symbols
main 为图标题
sub 为图下标题
col.main 为设置图标题颜色
font.main 为设置图标题字体
cel 为symble 大小
lty 为折线类型 1为实线, 2为虚线
二、折线图
## 折线图只需在plot函数中加入type=“ ?” ##
> plot(week,x,col="red",pch=22,bg="yellow",xlim=c(0,6),ylim=c(0,30),lwd=2,xlab="WEEK",ylab="STUDENT",main="lesson",sub="class",col.main="green",font.main=2,asp=0,cex=1.2,type="b",lty=1)
type
what type of plot should be drawn. Possible types are
· "p" for points,
· "l" for lines,
· "b" for both,
· "c" for the lines part alone of "b",
· "o" for both ‘overplotted’,
· "h" for ‘histogram’ like (or ‘high-density’) vertical lines,
· "s" for stair steps,
· "S" for other steps, see ‘Details’ below,
· "n" for no plotting.
## 添加一条线 使用函数lines()##
>lines(week,y,col="green",pch=16,bg="yellow",xlim=c(0,6),ylim=c(0,30),lwd=2,xlab="WEEK",ylab="STUDENT",main="lesson",sub="class",col.main="green",font.main=2,asp=0,cex=1.2,type="b",lty=2)
## 对图添加栅格 使用grid()函数 ##
grid(nx=6,ny=6,lwd=2)
如果只需横轴上有栅格,则ny=NA
## 如何在图中添加一条直线 用abline() 函数##
> abline(h=18,col="black",lty=1,lwd=2)
## 如何添加图例 用legend() 函数##
>legend("topright",legend=c("x","y"),pch=c(22,16),col=c("red","green"),lwd=2,lty=c(1,2))
当然topright 还可以用坐标位置代替(x,y)
三 平滑曲线图
## 使用函数 spline(x,y,n=?) ##
> sp=spline(week,x,n=1000)
> sp1=spline(week,y,n=1000)
n值表示平滑程度
> plot(sp,col="red",type="l",xlim=c(0,6),ylim=c(0,30),lwd=2,xlab="WEEK",ylab="STUDENT",main="lesson",sub="class",col.main="green",font.main=2)
> lines(sp1,col="green",type="l",xlim=c(0,6),ylim=c(0,30),lwd=2,xlab="WEEK",ylab="STUDENT",main="lesson",sub="class",col.main="green",font.main=2)
> legend("topright",legend=c("x","y"),col=c("red","green"),lwd=2,lty=c(1,2))
转载自:http://blog.sina.com.cn/s/blog_5d188bc40102vu2b.html