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)


