ggplot

library(ggplot2)
ggplot(data=mtcars, aes(x=wt, y=mpg)) +    #設(shè)定數(shù)據(jù)來(lái)源和x、y變量
      geom_point() +    #創(chuàng)建散點(diǎn)圖
      labs(title="Automobile Data", x="Weight", y="Miles Per Gallon")  #添加注釋?zhuān)ㄝS標(biāo)簽和標(biāo)題)。
ggplot(data=mtcars, aes(x=wt, y=mpg)) +
     geom_point(pch=17, color="blue", size=2) +    #點(diǎn)的形狀為三角形,點(diǎn)的大小加倍,顏色為藍(lán)色
     geom_smooth(method="lm", color="red", linetype=2) +
     #增加了一條“平滑”曲線(xiàn)。
     #這里需要線(xiàn)性擬合(method="lm"),并且產(chǎn)生一條紅色虛線(xiàn),默認(rèn)線(xiàn)條尺寸為1。
     #默認(rèn)情況下,平滑的曲線(xiàn)包括在95%的置信區(qū)間(較暗帶)內(nèi)。
     labs(title="Automobile Data", x="Weight", y="Miles Per Gallon")

ggplot2包提供了分組和小面化(faceting)的方法。
分組指的是在一個(gè)圖形中顯示兩組或多組觀(guān)察結(jié)果。
小面化指的是在單獨(dú)、并排的圖形上顯示觀(guān)察組。
ggplot2包在定義組或面時(shí)使用因子。

#首先,將am、vs和cyl變量轉(zhuǎn)化為因子
#cyl是汽車(chē)發(fā)動(dòng)機(jī)汽缸的數(shù)量
#am和vs是刻面變量,cyl是分組變量
mtcars$am <- factor(mtcars$am, levels=c(0,1),labels=c("Automatic", "Manual"))
mtcars$vs <- factor(mtcars$vs, levels=c(0,1),labels=c("V-Engine", "Straight Engine"))
mtcars$cyl <- factor(mtcars$cyl)      
ggplot(data=mtcars, aes(x=hp, y=mpg,shape=cyl, color=cyl)) +
    geom_point(size=3) +
    facet_grid(am~vs) +
    labs(title="Automobile Data by Engine Type",x="Horsepower", y="Miles Per Gallon")
data(singer, package="lattice")
ggplot(singer, aes(x=height)) + geom_histogram()
ggplot(singer, aes(x=voice.part, y=height)) + geom_boxplot()
#創(chuàng)建直方圖時(shí)只有變量x是指定的,但創(chuàng)建箱線(xiàn)圖時(shí)變量x和y都需要指定。
#geom_histgrom()函數(shù)在y變量沒(méi)有指定時(shí)默認(rèn)對(duì)y軸變量計(jì)數(shù)。

library(car)
data(Salaries, package="carData")
ggplot(Salaries, aes(x=rank, y=salary)) +
geom_boxplot(fill="cornflowerblue",color="black", notch=TRUE)+
geom_point(position="jitter", color="blue", alpha=.5)+
geom_rug(side="l", color="black")

data(singer, package="lattice")
ggplot(singer, aes(x=voice.part, y=height)) +
geom_violin(fill="lightblue") +
geom_boxplot(fill="lightgreen", width=.2)



?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容