R action 6

20171225(從有道遷移)

基本圖形

  1. 條形圖

    1. 簡單條形圖:

      1. 通過垂直的或水平的條形展示了類別型變量的分布(頻數(shù))
      2. 語法:barplot(height), 其中的height是一個向量或一個矩陣
      3. 選項horiz=TRUE會生成一幅水平條形圖
      4. 選項main可添加一個圖形標題,選項xlab和ylab則會分別添加x軸和y軸標簽
      library("vcd")
      counts <- table(Arthritis$Improved)
      barplot(counts,main="Simple Bar Plot",xlab="Imporvement",ylab="Frequency")
      
      
    2. 堆砌條形圖和分組條形圖

      1. 如果height是一個矩陣而不是一個向量,則繪圖結(jié)果將是一幅堆砌條形圖或分組條形圖。
      2. 若beside=FALSE(默認值),則矩陣中的每一列都將生成圖中的一個條形,各列中的值將給出堆砌的“子條”的高度。
      3. 若beside=TRUE,則矩陣中的每一列都表示一個分組,各列中的值將并列而不是堆砌
      --堆砌條形圖
      barplot(counts,main="Stacked Bar Plot",xlab="Treatment",ylab="Frequency",col=c("red","yellow","green"),legend=rownames(counts))
      
      --分組條形圖
      barplot(counts,main="Stacked Bar Plot",xlab="Treatment",ylab="Frequency",col=c("red","yellow","green"),legend=rownames(counts),beside=TRUE))
      
      --對legend的遮擋結(jié)果進行處理,設置xlim,heargs.legnd的參數(shù)值
      barplot(counts,main="Stacked Bar Plot",xlim=c(0, ncol(counts) + 1.5),xlab="Treatment",ylab="Frequency",col=c("red","yellow","green"),legend.text=rownames(counts), args.legend=list(x=ncol(counts) + 1.5,y=max(colSums(counts)),bty = "n"))
      
    3. 均值條形圖

      1. 條形圖并不一定要基于計數(shù)數(shù)據(jù)或頻率數(shù)據(jù)。
      2. 可以使用數(shù)據(jù)整合函數(shù)并將結(jié)果傳遞給barplot()函數(shù),來創(chuàng)建表示均值、中位數(shù)、標準差等的條形圖
      states <- data.frame(state.region,state.x77)
      means <- aggregate(states$Illiteracy,by=list(state.region),FUN=mean)
      means <- means[order(means$x),]
      barplot(means$x,names.arg=means$Group.1)
      
    4. 條形圖的微調(diào)

      1. cex.names調(diào)整字號
      2. names.arg你指定一個字符向量作為條形的標簽名
      3. par()函數(shù)也可以對圖形進行微調(diào)
      4. 詳細參數(shù)可以查看barplot的幫助文檔
    5. 為棘狀圖(spinogram)

      1. 棘狀圖對堆砌條形圖進行了重縮放,這樣每個條形的高度均為1,每一段的高度即表示比例。
      2. 棘狀圖可由vcd包中的函數(shù)spine()繪制。
  2. 餅圖

    1. 餅圖函數(shù):pie(x,labels),其中x是一個非負數(shù)值向量,表示每個扇形的面積,而labels則是表示各扇形標簽的字符型向量。
    2. 示例:
    --圖形設置,這樣四幅圖形就會被組合為一幅
    par(mfrow=c(2,2))                             
    slices <- c(10, 12,4, 16, 8) 
    lbls <- c("US", "UK", "Australia", "Germany", "France")
    
    pie(slices, labels = lbls, main="Simple Pie Chart")
    
    pct <- round(slices/sum(slices)*100)            
    lbls2 <- paste(lbls," ",pct,"%",sep="")
    pie(slices,labels = lbls, col=rainbow(length(lbls)),
        main="Pie Chart with Percentages")
    
    library(plotrix)                                               
    pie3D(slices, labels=lbls,explode=0.1, main="3D Pie Chart ")
    
    mytable <- table(state.region)                                   
    lbls3 <- paste(names(mytable), "\n", mytable, sep="")
    pie(mytable, labels = lbls3, 
        main="Pie Chart from a dataframe\n (with sample sizes)")
    
    par(opar)
    
    1. 扇形圖:是通過plotrix包中的fan.plot()函數(shù)實現(xiàn)的

      fan.plot(slices,labels=lbls,main="Simple Fan Chart")

  3. 直方圖

    1. 在X 軸上將值域分割為一定數(shù)量的組,在Y軸上顯示相應值的頻數(shù),展示了連續(xù)型變量的分布;
    2. 函數(shù):hist(x)
      1. x是一個由數(shù)據(jù)值組成的數(shù)值向量
      2. 參數(shù)freq=FALSE表示根據(jù)概率密度而不是頻數(shù)繪制圖形
      3. 參數(shù)breaks用于控制組的數(shù)量
      4. 在定義直方圖中的單元時,默認將生成等距切分。
    3. 示例
    # simple histogram                                   
    hist(mtcars$mpg)
    
    # colored histogram with specified number of bins
    # 將組數(shù)指定為12,使用紅色填充條形      
    hist(mtcars$mpg, 
         breaks=12, 
         col="red", 
         xlab="Miles Per Gallon", 
         main="Colored histogram with 12 bins")
    
    # colored histogram with rug plot, frame, and specified number of bins 
    
    # 在上圖的基礎上疊加了條密度曲線和軸須圖(rug plot)。這條密度曲線是一個核密度估計,它為數(shù)據(jù)的分布提供了一種更加平滑的描述。
    # 軸須圖是實際數(shù)據(jù)值的一種一維呈現(xiàn)方式。
    # 如果數(shù)據(jù)中有許多結(jié)(數(shù)據(jù)中出現(xiàn)相同的值,稱為結(jié)),可以使用rug(jitter(mtcars$mpg,amount=0.02)) 將軸須圖的數(shù)據(jù)打散:
    
    #使用lines()函數(shù)疊加了藍色、雙倍默認線條寬度的曲線
    
    hist(mtcars$mpg, 
         freq=FALSE, 
         breaks=12, 
         col="red", 
         xlab="Miles Per Gallon", 
         main="Histogram, rug plot, density curve")  
    rug(jitter(mtcars$mpg)) 
    lines(density(mtcars$mpg), col="blue", lwd=2)
    
    # histogram with superimposed normal curve (Thanks to Peter Dalgaard)  
    
    #在圖2疊加在上面的正態(tài)曲線和一個將圖形圍繞起來盒型
    x <- mtcars$mpg 
    h<-hist(x, 
            breaks=12, 
            col="red", 
            xlab="Miles Per Gallon", 
            main="Histogram with normal curve and box") 
    xfit<-seq(min(x),max(x),length=40) 
    yfit<-dnorm(xfit,mean=mean(x),sd=sd(x)) 
    yfit <- yfit*diff(h$mids[1:2])*length(x) 
    lines(xfit, yfit, col="blue", lwd=2)
    box()
    
  4. 核密度圖

    1. ==核密度估計==是用于估計隨機變量概率密度函數(shù)的一種非參數(shù)方法;
    2. 函數(shù)plot(density(x))
      1. x是一個數(shù)值型向量。
      2. plot()函數(shù)會創(chuàng)建一幅新的圖形,向一幅已經(jīng)存在的圖形上疊加一條密度曲線,可以使用lines()函數(shù)
    3. 示例
    # returns the density data  
    d <- density(mtcars$mpg) 
    # plots the results 
    plot(d) 
    
    #將曲線修改為藍色,使用實心紅色填充了曲線下方的區(qū)域,并添加了棕色的軸須圖。
    plot(d, main="Kernel Density of Miles Per Gallon")       
    #polygon()函數(shù)根據(jù)頂點的x和y坐標(本例中由density()函數(shù)提供)繪制了多邊形
    polygon(d, col="red", border="blue")                     
    rug(mtcars$mpg, col="brown") 
    
    1. 核密度圖可用于比較組間差異,用sm包中的sm.density.compare()函數(shù)可向圖形疊加兩組或更多的核密度圖。使用格式為sm.density.compare(x,factor)
      1. x是一個數(shù)值型向量
      2. factor是一個分組變量
      3. 示例:
      #比較擁有4個、6個或8個汽缸車型的每加侖汽油行駛英里數(shù)
      
      #將所繪制的線條設置為雙倍寬度
      par(lwd=2)                                                       
      library(sm)
      attach(mtcars)
      
      # create value labels 
      # 變量cyl是一個以4、6或8編碼的數(shù)值型變量
      # 為了向圖形提供值的標簽,這里cyl轉(zhuǎn)換為名為cyl.f的因子
      cyl.f <- factor(cyl, levels= c(4, 6, 8),                         
                      labels = c("4 cylinder", "6 cylinder", "8 cylinder")) 
      
      # plot densities 
      sm.density.compare(mpg, cyl, xlab="Miles Per Gallon")                
      title(main="MPG Distribution by Car Cylinders")
      
      # add legend via mouse click
      colfill<-c(2:(2+length(levels(cyl.f)))) 
      cat("Use mouse to place legend...","\n\n")
      
      #參數(shù)值locator(1)表示用鼠標點擊想讓圖例出現(xiàn)的位置來交互式地放置這個圖例
      legend(locator(1), levels(cyl.f), fill=colfill) 
      detach(mtcars)
      par(lwd=1)
      
  5. 箱線圖

    1. 通過繪制連續(xù)型變量的五數(shù)總括,即最小值、下四分位數(shù)(第25百分位數(shù))、中位數(shù)(第50百分位數(shù))、上四分位數(shù)(第75百分位數(shù))以及最大值,描述了連續(xù)型變量的分布
    2. 箱線圖能夠顯示出可能為離群點(范圍±1.5*IQR以外的值,IQR表示四分位距,即上四分位數(shù)與下四分位數(shù)的差值)的觀測
    3. 函數(shù):boxplot(x) ; 示例:boxplot(mtcars$mpg,main="Box Plot",ylab="Miles Per Gallon")
    4. 執(zhí)行boxplot.stats(mtcars$mpg)即可輸出用于構(gòu)建圖形的統(tǒng)計量
    5. 使用并列箱線圖進行跨組比較,格式:```boxplot(formula,data=dataframe)
      1. formula是一個公式。示例公式:
        • 公式y(tǒng) ~A,將為類別型變量A的每個值并列地生成數(shù)值型變量y的箱線圖。
        • 公式y(tǒng) ~ A*B,將為類別型變量A和B所有水平的兩兩組合生成數(shù)值型變量y的箱線圖
      2. dataframe代表提供數(shù)據(jù)的數(shù)據(jù)框(或列表)。
      3. 參數(shù)varwidth=TRUE將使箱線圖的寬度與其樣本大小的平方根成正比。
      4. 參數(shù)horizontal=TRUE可以反轉(zhuǎn)坐標軸的方向
      5. 通過添加notch=TRUE,可以得到含凹槽的箱線圖
      6. 示例:
      boxplot(mpg~cyl,data=mtcars, varwidth=TRUE,col="red",main="Car Mileage Data", xlab="Number of Cylinders",ylab="Miles Per Gallon")
      
      # 含凹槽的箱線圖
      boxplot(mpg~cyl,data=mtcars, notch=TRUE, varwidth=TRUE,col="red",main="Car Mileage Data", xlab="Number of Cylinders", ylab="Miles Per Gallon")
      
      # 個分組因子繪制箱線圖
       boxplot(mpg ~ am.f * cyl.f ,data=mtcars, varwidth=TRUE,col=c("gold","darkgreen"),main="MPG Distribution by Auto Type",xlab="Auto Type")
      
      
  6. 小提琴圖

    1. 小提琴圖(violin plot)是箱線圖變種;
    2. 小提琴圖是箱線圖與核密度圖的結(jié)合;
    3. 使用vioplot包中的vioplot()函數(shù)繪制;
    4. 格式:vioplot(x1,x2,...,names=,cols=)
      1. x1,x2,…表示要繪制的一個或多個數(shù)值向量(將為每個向量繪制一幅小提琴圖);
      2. 參數(shù)names是小提琴圖中標簽的字符向量;
      3. col是一個為每幅小提琴圖指定顏色的向量。
    5. 示例
    install.packages("vioplot")
    library("vioplot")
    
    x1 <- mtcars$mpg[mtcars$cyl==4]
    x2 <- mtcars$mpg[mtcars$cyl==6]
    x3 <- mtcars$mpg[mtcars$cyl==8]
    
    vioplot(x1,x2,x3,names=c("4 cyl","6 cyl","8 cyl"),col="gold")
    
    
  7. 點圖

    1. 點圖在簡單水平刻度上繪制大量有標簽值的方法;
    2. 函數(shù):dotchart(x,labels=)
      1. x是一個數(shù)值向量;
      2. labels是由每個點的標簽組成的向量;
      3. cex可控制標簽的大小;
      4. 參數(shù)groups來選定一個因子,用以指定x中元素的分組方式;
      5. 當使用groups時,參數(shù)gcolor可以控制不同組標簽的顏色
    3. 示例
    dotchart(mtcars$mpg,labels=row.names(mtcars),cex=.7,main="Gas Mileage for Car Models",xlab="Miles Per Gallon")
    
    # 分組、排序、著色后的點圖
    # 根據(jù)每加侖汽油行駛英里數(shù)(從最低到最高)對數(shù)據(jù)框mtcars進行排序
    x <- mtcars[order(mtcars$mpg),]
    
    # 數(shù)值向量cyl被轉(zhuǎn)換為一個因子
    x$cyl <- factor(x$cyl)
    x$color[x$cyl==4] <- "red"
    x$color[x$cyl==6] <- "blue"
    x$color[x$cyl==8] <- "darkgreen"
    dotchart(x$mpg,labels=row.names(x),cex=.7,groups=x$cyl,gcolor="black",color=x$color,pch=19,main="Gas Milesage for Car Models\ngrouped by cylinder",xlab="Miles Per Gallon")
    
    # 說明:隨著汽缸數(shù)的減少,每加侖汽油行駛的英里數(shù)有了增加。但你同時也看到了例外。例如,Pontiac Firebird有8個汽缸,但較六缸的Mercury 280C和Valiant的行駛英里數(shù)更多。六缸的Hornet 4 Drive與四缸的Volvo 142E的每加侖汽油行駛英里數(shù)相同。
    # 同樣明顯的是,Toyota Corolla的油耗最低,而Lincoln Continental和Cadillac Fleetwood是英里數(shù)較低一端的離群點
    
    
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容