1. 安裝和讀取: install.packages("ggplot2")
library(ggplot2)
2. 畫點圖(泰坦尼克數據):
Titanic=read.csv("https://goo.gl/4Gqsnz") #從網絡讀取數據
ggplot(data=Titanicclean,aes(x=Age,y=Fare))+geom_point(aes(col=factor(Pclass)))
# aes是軸,geom_point是畫點圖,col=factor()是按這個變量分顏色
3. 相同數據畫點圖+線圖,並加總標題:
ggplot(data=Titanicclean,aes(x=Age,y=Fare))+geom_line(aes(col=factor(Pclass)))+geom_point(aes(col=factor(Pclass))) +ggtitle("AAAA")
# geom_line是畫線圖,ggtitle是加標題
格式爲:ggplot(data=Titanicclean,aes(x=Age,y=Fare,col=factor(Pclass)))+geom_line()+geom_point()
4. 加回歸曲線和置信區間:
ggplot(data=Titanicclean,aes(x=Age,y=Fare))+geom_point(aes(col=factor(Pclass)))+geom_smooth(method="lm",se=T)
# lm是線性迴歸,se=TRUE是顯示置信區間
5. 調整散點的大小:
ggplot(data=Titanicclean,aes(x=Age,y=Fare))+geom_point(aes(col=factor(Pclass),size=1.5))+geom_smooth(method="lm",se=T)
# size=多少就是增大或縮小(0.4)多少倍
6. 分組條圖:
ggplot(data=Titanicclean,aes(x=Sex,fill=as.factor(Survived)))+geom_bar(position ="dodge")+facet_grid(~Pclass)
#as.factor表示把這個變量變成factor類別的分類變量,position=dodge 表示並列展示,如爲stack則表示疊加展示;facet_grid表示按照某變量分組展示
7. 保存圖片
ggsave("myplot.pdf",width = 10,height = 7,units = "in")
#保存成什麼類型就命名爲什麼類型,也可以是myplot.png等。unit代表寬度和高度的單位,in是英寸。
如果保存成pdf文件還有另外一種方法,順便展示一下寫for loop,如何將多張圖保存到一個PDF文件裏:
pdf(file = "mydata.pdf",width = 10,height = 7) #pdf命令是開始printing into the file
for(i in sort(unique(Pclass))){ #對每一個艙位等級的人分別畫圖
print(
ggplot(data=titanicC[Pclass=i,],aes(x=Age,y=Fare, col=as.factor(Pclass)))+
geom_point()+
geom_smooth(method = "lm",se=T)+ #線性擬合,顯示置信區間
scale_y_log10() #對Y周取log10對數值
)
}
dev.off() #dev.off是stop printing