R语言中有关绘图的包:base、grid、lattice及ggplot2

1.lattice包

可生成栅栏图形


[plain] view plaincopy


1. library(lattice)  
2. histogram(~height|voice.part,data=singer,  
3.           main="Distribution of Heights by Voice Pitch",  
4.           xlab="Height(inches)")

height是因变量,voice.part被称作条件变量(conditioning variable)

该代码对八个声部的每一个都创建一个直方图

rattle R语言 r语言lattice_自定义



2.lattice绘图示例


[plain] view plaincopy

1. install.packages("lattice")  
2. library(lattice)  
3. attach(mtcars)  
4. gear<-factor(gear,levels=c(3,4,5),labels=c("3 gears","4 gears","5 gears"))  
5. cyl<-factor(cyl,levels=c(4,6,8),labels=c("4 cylinders","6 cylinders","8 cylinders"))  
6. densityplot(~mpg,main="Density Plot",xlab="Miles per Gallon")


rattle R语言 r语言lattice_图例_02





[plain] view plaincopy



  1. densityplot(~mpg|cyl,main="Density Plot by Number of Cylinders")  



rattle R语言 r语言lattice_rattle R语言_03





[plain] view plaincopy


1. bwplot(cyl~mpg|gear,main="Box Plots by Cylinders and Gears",xlab="Miles per Gallon",ylab="cylinders")


rattle R语言 r语言lattice_rattle R语言_04



[plain] view plaincopy


1. xyplot(mpg~wt|cyl*gear,main="Scatter Plots by Cylinders and Gears",xlab="Car Weight",ylab="Miles per Gallon")


rattle R语言 r语言lattice_rattle R语言_05



[plain] view plaincopy


1. cloud(mpg~wt*qsec|cyl,main="3D Scatter Plots by Cylinders")


rattle R语言 r语言lattice_自定义_06



[plain] view plaincopy


1. dotplot(cyl~mpg|gear,main="Dot Plots by Number of Gears and Cylinders",xlab="Miles Per Gallon")


rattle R语言 r语言lattice_自定义_07







3.条件变量


通常条件变量是因子,但若想以连续变量为条件,一种方法是利用R中的cut()函数将连续型变量转换为离散变量;另外,lattice包提供了一些将连续型变量转化为瓦块(shingle)数据结构的函数。各连续变量会被分割到一系列(可能)重叠的数值范围内。



[plain] view plaincopy



    1. library(lattice)  
    2. displacement<-equal.count(mtcars$disp,number=3,overlap=0)  
    3. xyplot(mpg~wt|displacement,data=mtcars,  
    4.        main="Miles per Gallon vs.Weight by Engine Displacement",  
    5.        xlab="Weight",ylab="Miles per Gallon",  
    6.        layout=c(3,1),aspect=1.5)



    rattle R语言 r语言lattice_条件变量_08









    4.面板函数


    默认的面板函数服从如下命名惯例:panel.graph_function,其中graph_function是该水平绘图函数,

    如xyplot(mpg~wt|displacement,data=mtcars)也可写为xyplot(mpg~wt|displacement,data=mtcars,panel=panel.xyplot)

    可以使用自定义函数替换默认的面板函数,也可将lattice包中的50多个默认面板中的某个或多个整合到自定义的函数中。自定义面板函数具有极大的灵活性,可随意设计输出结果以满足要求。

    Eg:



    [plain] view plaincopy


    1. displacement<-equal.count(mtcars$disp,number=3,overlap=0)  
    2. mypanel<-function(x,y){  
    3.   panel.xyplot(x,y,pch=19)  
    4.   panel.rug(x,y)  
    5.   panel.grid(h=-1,v=1)  
    6.   panel.lmline(x,y,col="red",lwd=1,lty=2)  
    7. }  
    8. xyplot(mpg~wt|displacement,data=mtcars,  
    9.        laycout=c(3,1),  
    10.        aspect=1.5,  
    11.        main="Miles per Gallon vs.Weight by Engine Displacement",  
    12.        xlab="Weight",  
    13.        ylab="Miles per Gallon",  
    14.        panel=mypanel)


    rattle R语言 r语言lattice_条件变量_09



    自定义面板函数和额外选项的xyplot



    [plain] view plaincopy


    1. library(lattice)  
    2. mtcars$transmission<-factor(mtcars$am,levels=c(0,1),  
    3.                             labels=c("Automatic","Manual"))  
    4. panel.smoother<-function(x,y){  
    5.   panel.grid(h=-1,v=-1)  
    6.   panel.xyplot(x,y)  
    7.   panel.loess(x,y)  
    8.   panel.abline(h=mean(y),lwd=2,lty=2,col="green")  
    9. }  
    10. xyplot(mpg~disp|transmission,data=mtcars,  
    11.        scales=list(cex=.8,col="red"),  
    12.        panel=panel.smoother,  
    13.        xlab="Displacement",ylab="Miles per Gallon",  
    14.        main="MGP vs Displacement by Transmission Type",  
    15.        sub="Dotted lines are Group Means",aspect=1)



    5.分组变量


    若一个lattice图形表达式含有条件变量时,将会生成在该变量各个水平下的面板,若想将结果叠加到一起,则可以将变量设定为分组变量(grouping variable)。



    [plain] view plaincopy



      1. library(lattice)  
      2. mtcars$transmission<-factor(mtcars$am,levels=c(0,1),  
      3.                             labels=c("Automatic","Manual"))  
      4. densityplot(~mpg,data=mtcars,  
      5.             group=transmission,  
      6.             main="MPG Distribution by Transmission Type",              
      7.             xlab="Miles per Gallon",  
      8.             auto.key=TRUE)


      rattle R语言 r语言lattice_条件变量_10



      可以修改auto.key的值来更改图例的位置

      auto.key=list(space="right",columns=1,title="Transmission")

      自定义图例并含有分组变量的核密度曲线图




      [plain] view plaincopy


      1. library(lattice)  
      2. mtcars$transimission<-factor(mtcars$am,levels=c(0,1),  
      3.                              labels=c("Automatic","Manual"))  
      4. colors=c("red","green")  
      5. lines=c(1,2)  
      6. points=c(16,17)  
      7. key.trans<-list(title="Transimission",  
      8.                 space="botton",columns=2,  
      9.                 text=list(levels(mtcars$transimission)),  
      10.                 points=list(pch=points,col=colors),  
      11.                 lines=list(col=colors,lty=lines),  
      12.                 cex.title=1,cex=.9)  
      13. densityplot(~mpg,data=mtcars,  
      14.             group=transimission,  
      15.             main="MPG Distribution by Tranmission Type",  
      16.             xlab="Miles per Gallon",  
      17.             pch=points,lty=lines,col=colors,  
      18.             lwd=2,jitter=.005,  
      19.             key=key.trans)




      分组变量和条件变量同时包含在一幅图形中的eg:



      [plain] view plaincopy



        1. library(lattice)  
        2. colors<-"darkgreen"  
        3. symbols<-c(1:12)  
        4. linetype<-c(1:3)  
        5. key.species<-list(title="Plant",  
        6.                   space="right",  
        7.                   text=list(levels(CO2$Plant)),  
        8.                   points=list(pch=symbols,col=colors))  
        9. xyplot(uptake~conc|Type*Treatment,data=CO2,  
        10.        group=Plant,  
        11.        type="o",  
        12.        pch=symbols,col=colors,lty=linetype,  
        13.        main="Carbon Dioxide Uptake\n in Grass Plants",  
        14.        ylab=expression(paste("Uptake",bgroup("(",italic(frac("umol","m"^2)),")"))),  
        15.        xlab=expression(paste("Concentration",bgroup("(",italic(frac(mL.L)),")"))),  
        16.        sub="Grass Spcecies:Echinochloa crus-galli",  
        17.        key=key.species)



        rattle R语言 r语言lattice_rattle R语言_11





        6.图形参数


        par()函数仅对R中简单的图形系统生成的图形有效,对于lattice图形来说这些设置是无效的。

        在lattice图形中,lattice函数默认的图形参数包含在一个很大的列表对象中,可通过trellis.par.get()函数来获取

        trellis.par.set()函数来修改

        show.settings()函数可展示当前的图形设置情况

        eg:



        [plain] view plaincopy


        1. show.settings()  
        2. mysettings<-trellis.par.get()  
        3. mysettings$superpose.symbol  
        4. mysettings$superpose.symbol$pch<-c(1:10)  
        5. trellis.par.set(mysettings)  
        6. show.settings()




        7.页面摆放


        par()函数可在一个页面上摆放多个图形,因lattice函数不识别par()设置,故需要新方法。可将lattice图形存储到对象中,然后利用plot()函数中的split=或position=选项来进行控制。

        split选项的格式为:

        split=c(placement row,placementcolumn,total number of rows,total number of columns)

        eg1 :



        [plain] view plaincopy


        1. library(lattice)  
        2. graph1<-histogram(~height|voice.part,data=singer,  
        3.                   main="Height of Choral Singers by Voice Part")  
        4. graph2<-densityplot(~height,data=singer,group=voice.part,plot.points=FALSE,auto.key=list(columns=4))  
        5. plot(graph1,split=c(1,1,1,2))  
        6. plot(graph2,split=c(1,2,1,2),newpage=FALSE)


        rattle R语言 r语言lattice_条件变量_12



        eg2:



        [plain] view plaincopy



          1. library(lattice)  
          2. graph1<-histogram(~height|voice.part,data=singer,  
          3.                   main="Height of Choral Singers by Voice Part")  
          4. graph2<-densityplot(~height,data=singer,group=voice.part,plot.points=FALSE,auto.key=list(columns=4))  
          5. plot(graph1,postion=c(0,.3,1,1))  
          6. plot(graph2,postion=c(0,0,1,.3),newpage=FALSE)



          rattle R语言 r语言lattice_rattle R语言_13



          使用position=选项可以对大小和摆放方式进行更多的控制

          positon=c(xlim,ylim,xmax,ymax)


          index.cond=选项可设定条件水平的顺序




          8.ggplot2包


          qplot(x,y,data=,color=,shape=,size=,alpha=,geom=,method=,formula=,facets=,xlim=,ylim=,xlab=,ylab=,main=,sub=)

          color把变量的水平与符号颜色、形状或大小联系起来。对于直线图,colo将把线条颜色与变量水平联系起来,对于密度图和箱线图fill将把填充颜色与变量联系起来。图例会被自动绘制。

          geom设定定义图形类型的几何形状,geom选项是一个单条目或多条目的字符向量,包括“point”、“smooth”、“boxplot”、“line”、“histogram”、“density”、“bar”和“jitter”。

           

          Eg:



          [plain] view plaincopy


          1. library(ggplot2)  
          2. mtcars$cylinder<-as.factor(mtcars$cyl)  
          3. qplot(mtcars$cylinder,mtcars$mpg,geom=c("boxplot","jitter"),  
          4.       fill=mtcars$cylinder,  
          5.       main="Box plots with superimposed data points",  
          6.       xlab="Number of Cylinders",  
          7.       ylab="Miles per Gallon")



          [plain] view plaincopy



            1. library(ggplot2)  
            2. transimission<-factor(mtcars$am,levels=c(0,1),  
            3.                       labels=c("Automatic","Manual"))  
            4. qplot(mtcars$wt,mtcars$mpg,  
            5.       color=transimission,shape=transimission,  
            6.       geom=c("point","smooth"),  
            7.       method="lm",formula=y~x,  
            8.       xlab="Weight",ylab="Miles Per Gallon",  
            9.       main="Regression Example")




            创建一个分面(栅栏)图



            [plain] view plaincopy


            1. library(ggplot2)  
            2. mtcars$cyl<-factor(mtcars$cyl,levels=c(4,6,8),  
            3.                    labels=c("4 cylinders","6 cylinders","8 cylinders"))  
            4. mtcars$am<-factor(mtcars$am,levels=c(0,1),  
            5.                   labels=c("Automatic","Manual"))  
            6. qplot(mtcars$wt,mtcars$mpg,facets=mtcars$am~mtcars$cyl,size=mtcars$hp)



            对lattice包中的singer数据进行绘图



            [plain] view plaincopy


            1. library(ggplot2)  
            2. data(singer,package="lattice")  
            3. qplot(height,data=singer,geom=c("density"),  
            4.       facets=voice.part~.,fill=voice.part)

            rattle R语言 r语言lattice_图例_14



            9.交互式图形


            与图形交互:鉴别点

            eg:



            [plain] view plaincopy



              1. plot(mtcars$wt,mtcars$mpg)  
              2. identify(mtcars$wt,mtcars$mpg,labels=row.names(mtcars))




              playwith包:



              [plain] view plaincopy


              1. install.packages("playwith",depend=TRUE)  
              2. library(playwith)  
              3. library(lattice)  
              4. playwith(  
              5.   xyplot(mpg~wt|factor(cyl)*factor(am),  
              6.          data=mtcars,subscripts=TRUE,  
              7.          type=c("r","p")))



              playwith()既对R基础图形有效,也对lattice和ggplot2图形有效


              使用latticist包,可通过栅栏图方式探索数据集,该包不仅提供了一个图形的用户界面,也可通过vcd包来创建新的图形,可与playwith整合到一起。



              [plain] view plaincopy



              1. library(latticist)  
              2. mtcars$cyl<-factor(mtcars$cyl)  
              3. mtcars$gear<-factor(mtcars$gear)  
              4. latticist(mtcars,use.playwith=TRUE)


              9.iplots的交互图形


              playwith和latticist包只能与单幅图形交互,而iplots包提供的交互方式则有所不同。

              该包提供了交互式马赛克图、柱状图、箱线图、平行坐标图、散点图和直方图,以及颜色刷,并可将它们结合在一起绘制。即可通过鼠标对观测点进行选择和识别,且对其中一幅图形的观测点突出显示时,其他被打开的图形将会自动突出显示相同的观测点。另外,可通过鼠标来收集图形对象(诸如点、条、线)和箱线图的信息。

              iplot函数

              ibar() 交互式柱状图

              ibox() 交互式箱线图

              ihist() 交互式直方图

              imap() 交互式地图

              imosaic() 交互式马赛克图

              ipcp() 交互式平等坐标图

              iplot() 交互式散点图

               



              [plain] view plaincopy


              1. iplots展示  
              2. library(iplots)  
              3. attach(mtcars)  
              4. cylinders<-factor(cyl)  
              5. gears<-factor(gear)  
              6. transimission<-factor(am)  
              7. ihist(mpg)  
              8. ibar(gears)  
              9. iplot(mpg,wt)  
              10. ibox(mtcars[c("mpg","wt","qsec","disp","hp")])  
              11. ipcp(mtcars[c("mpg","wt","qsec","disp","hp")])  
              12. imosaic(transimiission,cylinders)  
              13. detach(mtcars)  
              14.   
              15. rggobi  
              16. GGobi界面  
              17. install.packages("rggobi",depend=TRUE)  
              18. libary(rggobi)  
              19. g<-ggobi(mtcars)