R语言笔记-3-绘图

作者: 茶苯海 | 来源:发表于2016-12-06 01:49 被阅读84次
  • 基本作图plot
plot(faithful)
short.eruptions<-with(faithful,faithful[eruptions<3,])
#把喷发时间不超过3分钟的用红色点标出来
points(shorts.eruptions,col="red",pch=19)


#绘制一条紫色的垂直线
abline(v=3,color="purple")
#向数据图添加直线(回归)
fit<-lm(waiting~eruptions,data=faithful)
lines(faithful$eruptions,fitted(fit),col="blue")
#或者用
abline(a=coef(fit)[1],b=coef(fit)[2])
abline(fit,col="red")
  • type参数,控制绘制图形的类型
plot(LakeHuron,type="l",main='type="l"') #折线图
plot(LakeHuron,type="p",main='type="p"') #散点图
plot(LakeHuron,type="l",main='type="b"') #点线图
  • 灵活绘制其他数据图
with(mtcars,plot(mpg,disp))
with(mtcars,boxplot(disp,mpg))
with(mtcars,hist(mpg)
pairs(iris)       #绘制散点图矩阵
  • 控制数据图选项和参数
    1.标题和坐标轴标签
    main xlab ylab
    2.修改数据图选项
    坐标轴标签的样式las(label style)
    "0":默认,与坐标轴平行
    "1":始终水平
    "2":与坐标轴垂直
    "3":始终垂直
    坐标轴 axis()
    图例 legend
    文字 text
    3.外框类型
    bty(box type)参数
    "o":默认在绘图区域绘制一个完整的矩形
    "n":不绘制外框
    "l" "7" "c","u","]" 参数对应大写字母形状,确定绘制边框的方向。
    4.文字和坐标轴的字号
    cex(character expansion ratio)
    cex.main
    cex.lab
    cex.axis
    5.在单页中绘制多个数据图
    mfrow mfcol
    要绘制两个并排的数据图,mfrow=c(1,2)
old.par<-par(mfrow=c(1,2))
plot(faithful,main="Faithful eruptions")
plot(large.islands,main="Islands",ylab="Area")
par(old.par)  #恢复摄者

home文件夹 "~/"

  • 保存图片
png(filename="faithful.png")   #打开一个图形设备
plot(faithful)     #创建数据集
dev.off()          关闭图形设备

  • 使用lattice绘制切片图片
#绘制散点图,使用xyplot()函数
#formula: y~x |z 创建 y对x的数据图,以z为条件
xyplot(mpg ~ hp | factor(cyl), data=mtcars)
  • 添加趋势线(回归线)
    xyplot(mpg ~ hp | factor(cyl), data=mtcars),type=c("p","r"))
    其中,type="p"表示点,type="r"表示回归线

  • 使用主图修改数据图选项
    par.settings()函数可以使其与simpleTheme()函数结合。
    xyplot(mpg ~ hp | factor(cyl), data=mtcars),type=c("p","r"), par.settings=simpleTheme(col="red",col.line="blue")

  • 绘制不同类型图:
    散点图 xyplot() 柱状图 barchart() 箱型图 bwplot() 一维条带图 stripplot() 三维散点图 cloud() 三维曲面图 wireframe()
    绘制柱状图

barchart(car ~ mpg |factor(cyl),data=mtcars,
main="barchart",
scales=list(cex=0.5),
layout=c(3,1)

绘制箱型图

bwplot(~ hp |factor(cyl) ,data=mtcars,main="bwplot")

绘制分组数据

mtcars$cars <- rownames(mtcars)
mtcars$am <- with (mtcars, ifelse(am=0, "Automatic","Manual"))
barchart(cars ~ mpg | factor(cyl), data=mtcars,group=am,scales=list(cex=0.5),layout=c(3,1),
auto.key=TRUE)#添加图例

相关文章

网友评论

    本文标题:R语言笔记-3-绘图

    本文链接:https://www.haomeiwen.com/subject/ktlppttx.html