#散點圖
head(mtcars)
plot(mtcars$wt,mtcars$mpg)#基礎繪圖系統得到的散點圖
#ggplot中qplot()函數得到的散點圖得同樣圖
install.packages("ggplot2")
#若兩參數向量在同一數據框內
qplot(wt,mpg,data=mtcars)
#等價於
ggplot(mtcars,aes(x=wt,y=mpg))+geom_point()
#折線圖(type="l"爲線性)
head(pressure)
plot(pressure$temperature,pressure$pressure,type="l")#繪出第一條折線
#向圖形中添加數據點或多條折線
points(pressure$temperature,pressure$pressure)#添加數據點
lines(pressure$temperature,pressure$pressure/2,col="red")#添加更多折線
points(pressure$temperature,pressure$pressure/2,col="red")
#ggplot2中qplot()函數繪製折線圖
qplot(pressure$temperature,pressure$pressure,geom="line")
#等價於
qplot(temperature,pressure,data=pressure,geom="line")
#等價於
ggplot(pressure,aes(x=temperature,y=pressure))+geom_line()
#添加數據點
qplot(temperature,pressure,data=pressure,geom=c("line","point"))
#等價於
ggplot(pressure,aes(x=temperature,y=pressure))+geom_line()+geom_point()
#3、繪製條形圖——查看變量值、頻數、頻率
head(BOD)#查看數據,很簡單的數據
barplot(BOD$demand, names.arg=BOD$Time)#這裏高度表示demand的值,橫軸是time,自動分配,names.arg是在每個條下出現的名稱的向量
#用mtcars數據集中cyl繪製頻數條形圖
table(mtcars$cyl)
barplot(table(mtcars$cyl))
#ggplot繪製條形圖(qplot(geom)、ggplot+geom_)
qplot(mtcars$cyl)#mtcars連續型和離散型區別更加明顯
qplot(factor(mtcars$cyl))
#qplot(BOD$Time, BOD$demand, geom="bar", stat="identity")#橫軸變量是連續型的,會空出沒有值的變量,stat="identity"表示原始數據集不作任何統計變換
ggplot(BOD,aes(x=Time,y=demand))+geom_bar(stat="identity")
#qplot(factor(BOD$Time), BOD$demand, geom="bar", stat="identity")#橫軸變量改爲因子、離散的,不空出
##對於同一數據框裏面的變量繪製可以用下面的兩種方式
qplot(factor(cyl), data=mtcars)
ggplot(mtcars, aes(x=factor(cyl))) + geom_bar()
#4、繪製直方圖——查看一維數據分佈特徵
hist(mtcars$mpg)#默認間距,高度是每組內頻數
hist(mtcars$mpg, breaks=10)#breaks指定組距
#ggplot繪圖
qplot(mtcars$mpg)
#同一數據框可以用下面的方式
qplot(mpg, data=mtcars, binwidth=4)#binwidth設置寬度
ggplot(mtcars, aes(x=mpg)) + geom_histogram(binwidth=4)
#5、繪製箱線圖——對不同分佈比較
head(ToothGrowth)#以該數據集爲例,supp是因子變量,len是數值型連續型
plot(ToothGrowth$supp, ToothGrowth$len)#若x是因子,plot自動繪製箱線圖
boxplot(len ~ supp, data = ToothGrowth)#用boxplot繪製,指定y~x。是公式語法,效果一致
boxplot(len ~ supp + dose, data = ToothGrowth)#在x軸引入兩量的交互,按supp和dose對數據分組,繪製箱線。
##ggplot繪製箱線圖
qplot(ToothGrowth$supp, ToothGrowth$len, geom="boxplot")
qplot(supp, len, data=ToothGrowth, geom="boxplot")#針對同一數據框內變量
ggplot(ToothGrowth, aes(x=supp, y=len)) + geom_boxplot()#效果同上
qplot(interaction(ToothGrowth$supp, ToothGrowth$dose),ToothGrowth$len,geom="boxplot")
#interaction函數將分組變量組合在一起,繪製基於多分組變量的箱線圖,指定按supp和dose對數據分組
##同一數據框的情況
qplot(interaction(supp,dose),len, data=ToothGrowth, geom="boxplot")
ggplot(ToothGrowth, aes(x=interaction(supp, dose), y=len)) + geom_boxplot()
#6、繪製函數圖像——由公式繪製
curve(x^3 - 5*x, from=-4, to=4)#curve函數,第一部分公式,從-4到4的圖形
myfun=function(xvar)
{ 1/(1 + exp(-xvar + 10))}
curve(myfun(x), from=0, to=20)#以自定義函數繪圖
curve(1-myfun(x), add = TRUE, col = "red")#添加直線
qplot(c(0,20), fun=myfun, stat="function", geom="line")#指示向量作爲繪圖的x的區間
myfun=function(xvar)
+ { 1/(1 + exp(-xvar + 10))}
ggplot(data.frame(x=c(0,20)),aes(x=x)) + stat_function(fun=myfun,geom="line")#與上面相同