library(ggplot2)
#數(shù)據(jù)集
mtcars
#基本格式:ggplot(data,aes(x,y))+geom_xx()+annotate()+labs()
#aes是美化的意思镐牺,geom幾何宛乃,annotate是注釋惶岭,lab是標簽
#散點圖
ggplot(mtcars,aes(mpg,wt))+geom_point()
#線圖
ggplot(mtcars,aes(mpg,wt))+geom_line()
#點線圖
ggplot(mtcars,aes(mpg,wt))+geom_line()+geom_point()
#柱狀圖雄家,是連續(xù)變量效拭,變成因子
ggplot(mtcars,aes(cyl))+geom_bar()
class(mtcars$cyl)#類型
table(mtcars$cyl)#頻次
#轉換成因子恕齐,分類變量
ggplot(mtcars,aes(factor(cyl)))+geom_bar()
#分組匾灶,內部再分組(用am分類),形成堆積柱形圖
ggplot(mtcars,aes(factor(cyl),fill=factor(am)))+geom_bar()
#百分比的堆積柱形圖
ggplot(mtcars,aes(factor(cyl),fill=factor(am)))+geom_bar(position="fill")
#如果不想堆積再加,并排
ggplot(mtcars,aes(factor(cyl),fill=factor(am)))+geom_bar(position = "dodge")
#直方圖,一組數(shù)據(jù)
ggplot(mtcars,aes(mpg))+geom_histogram()
#密度圖
ggplot(mtcars,aes(mpg))+geom_density()
#分類,color是對點線的描繪吆豹,fill是填充
ggplot(mtcars,aes((mpg),fill=factor(vs)))+geom_density()#全是密集填充
ggplot(mtcars,aes((mpg),fill=factor(vs)))+geom_density(alpha=0.5)#透明度為0.5
ggplot(mtcars,aes((mpg),col=factor(vs)))+geom_density()#col是點線圖
#箱線圖(最小值毁葱,最大值垫言,中位數(shù),上下四分位數(shù))
ggplot(mtcars,aes(factor(vs),mpg))+geom_boxplot()
##分組作圖,qsec是連續(xù)型變量為參考指標倾剿,vs是二分變量
ggplot(mtcars,aes(wt,mpg,color=qsec))+geom_point()
ggplot(mtcars,aes(wt,mpg,color=factor(vs)))+geom_point()
#aes內與外的區(qū)別
ggplot(mtcars,aes(wt,mpg))+geom_point()
ggplot(mtcars,aes(wt,mpg))+geom_point(color="blue")
ggplot(mtcars,aes(wt,mpg,color="yellow"))+geom_point()#會將color當成一個分組變量而不是顏色
#分面作圖 facet_grid()
#1.軸刻度一致
#單變量作圖
ggplot(mtcars,aes(wt,mpg))+geom_point()+facet_grid(.~vs)#不能有逗號,是句號,按照橫軸排列
ggplot(mtcars,aes(wt,mpg))+geom_point()+facet_grid(vs~.)#是句號筷频,縱軸排列
#雙變量作圖
ggplot(mtcars,aes(wt,mpg))+geom_point()+facet_grid(am~vs)
#不同的縱軸刻度
ggplot(mtcars,aes(wt,mpg))+geom_point()+facet_grid(vs~.,scale="free")
#調整圖形,大小與形狀
ggplot(mtcars,aes(wt,mpg,color=factor(vs)))+geom_point(shape=3,size=3)
#文本注釋#標題#添加豎橫線#"加號",不能再第一行#互換XY
ggplot(mtcars,aes(wt,mpg,color=factor(vs)))+
? geom_point(shape=3,size=3)+
? annotate("text",x=4,y=20,label="yes")+
? labs(title="hello",x="sss",y="yyy")+
? geom_vline(xintercept = 3.5)+
? geom_hline(yintercept = 20)+
? coord_flip()
#調整刻度范圍#替換刻度值
ggplot(mtcars,aes(wt,mpg,color=factor(vs)))+
? geom_point(shape=3,size=3)+
? annotate("text",x=4,y=20,label="yes")+
? labs(title="hello",x="sss",y="yyy")+
? geom_vline(xintercept = 4)+
? geom_hline(yintercept = 2)+
? xlim(3,8)+
? ylim(15,25)+
? scale_x_continuous(breaks=c(3,3.75),labels = c("a","b"))