????話說“一圖勝千言”,在各類數(shù)據(jù)分析報(bào)告中經(jīng)常會看見各種各樣的圖形,例如折線圖、條形圖、箱線圖、點(diǎn)圖等。
其中折線圖可以反映某種現(xiàn)象的趨勢,本文利用R語言的ggplot2包,從頭帶您繪制各式各樣的線形圖。
一 ?繪制單條折線圖
載入數(shù)據(jù)及函數(shù)包
library(ggplot2)df <- data.frame(dose=c("A", "B", "C"), len=c(5.16, 10.10, 30))head(df)dose len1 A 5.162 B 10.103 C 30.00
1.1? 繪制基本的折線圖
ggplot(data=df, aes(x=dose, y=len, group=1)) +geom_line() 1.2 添加點(diǎn),并更改線型 和顏色
ggplot(data=df, aes(x=dose, y=len, group=1)) +geom_line(linetype = "dashed",color="red")+ geom_point() 1.3 添加箭頭
library(grid)ggplot(data=df, aes(x=dose, y=len, group=1))+geom_line(arrow = arrow())+geom_point()#自定義箭頭類型myarrow=arrow(angle = 15, ends = "both", type = "closed")ggplot(data=df, aes(x=dose, y=len, group=1)) +geom_line(arrow=myarrow)+geom_point()
1.4 附贈
ggplot(data=df, aes(x=dose, y=len, group=1)) + geom_step()+ geom_point() 注:因?yàn)闄M坐標(biāo)的屬性為因子(離散型的字符轉(zhuǎn)換為因子),所以需要添加‘group = 1’的設(shè)置。
二 繪制多條折線圖
設(shè)置數(shù)據(jù)
df2 <- data.frame(supp=rep(c("Case", "Control"), each=3), dose=rep(c("A", "B", "C"),2),len=c(6.8, 15, 38, 5.16, 10.10, 30))head(df2)supp dose len1 Case A 6.802 Case B 15.003 Case C 38.004 Control A 5.165 Control B 10.106 Control C 30.00
2.1 繪制多條折線圖,更改線型
ggplot(data=df2, aes(x=dose, y=len, group=supp))+geom_line(linetype="dashed", color="blue", size=1.2)+geom_point(color="red", size=3)
2.2 分組更改線型和點(diǎn)的形狀
ggplot(df2, aes(x=dose, y=len, group=supp)) +geom_line(aes(linetype=supp))+geom_point(aes(shape=supp))
2.3 自定義更改線型
ggplot(df2, aes(x=dose, y=len, group=supp)) +geom_line(aes(linetype=supp))+geom_point()+scale_linetype_manual(values=c("twodash", "dotted"))
2.4 更改顏色
p <- ggplot(df2, aes(x=dose, y=len, group=supp)) +geom_line(aes(color=supp))+geom_point(aes(color=supp))p
其他自定義顏色方式:
# Use custom color palettesp+scale_color_manual(values=c("#E69F00", "#56B4E9"))# Use brewer color palettesp+scale_color_brewer(palette="Dark2")# Use grey scalep +scale_color_grey() + theme_classic()
2.5 添加誤差棒
利用ToothGrowth數(shù)據(jù)集,首先分組計(jì)算每一分組的均值和標(biāo)準(zhǔn)差,整理成如下格式:
supp dose len sd1 OJ 0.5 13.23 4.4597092 OJ 1.0 22.70 3.9109533 OJ 2.0 26.06 2.6550584 VC 0.5 7.98 2.7466345 VC 1.0 16.77 2.5153096 VC 2.0 26.14 4.797731
繪制添加誤差棒的折線圖
ggplot(df3, aes(x=dose, y=len, group=supp, color=supp)) +geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.1) +geom_line() +geom_point()+???scale_color_brewer(palette="Paired")+theme_minimal()
注:可以使用position_dodge 參數(shù),防止errorbars重疊
三 折線圖匯總展示
ggplot(df3, aes(x=dose, y=len, group = supp, color=supp))+geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.1,position=position_dodge(0.05)) +geom_line(aes(linetype=supp)) +geom_point(aes(shape=supp))+labs(title="Plot of lengthby dose",x="Dose (mg)", y = "Length")+theme_classic()+scale_color_manual(values=c('#999999','#E69F00'))
四 參考資料
ggplot2:數(shù)據(jù)分析與圖形藝術(shù)
http://www.sthda.com/english/wiki/ggplot2-essentials
好了,就是這么簡單,輸出基本圖形后,根據(jù)自己的喜好進(jìn)行細(xì)節(jié)的調(diào)整即可。