引言
光光展示數(shù)據(jù)對可視化來說,遠(yuǎn)遠(yuǎn)不夠。還有其他很多信息能夠幫助讀者解釋你的數(shù)據(jù)。除了標(biāo)簽、坐標(biāo)軸、圖例外,還能夠增加注釋,比如強(qiáng)調(diào)圖畫的某一區(qū)域,添加描述性文本等。
添加文本注釋
你可以在圖形中添加文本,增加可讀性。我們在annotate函數(shù)中設(shè)置text參數(shù)即可。
1
2
3
4
5
6
7
8
9
|
library(ggplot2) library(gcookbook) p <- ggplot(faithful, aes(x=eruptions, y=waiting)) + geom_point() p + annotate( "text" , x=3, y=48, label= "Group 1" ) + annotate( "text" , x=4.5, y=66, label= "Group 2" ) #由于設(shè)置的文本會覆蓋原來的圖中對應(yīng)的位置,可以改變文本的透明度或者顏色 p + annotate( "text" , x=3, y=48, label= "Group 1" , alpha=.1) + annotate( "text" , x=4.5, y=66, label= "Group 2" , family= "serif" , fontface= "italic" , colour= "darkred" , size=3) |
添加數(shù)學(xué)表達(dá)式注釋
我們也可以在圖形中注釋數(shù)學(xué)表達(dá)式。在annotate中增加parse=TRUE參數(shù)即可。
1
2
3
4
|
p <- ggplot(data.frame(x=c(-3,3)), aes(x=x)) + stat_function(fun = dnorm) p + annotate( "text" , x=2, y=0.3, parse=TRUE, label= "frac(1, sqrt(2 * pi)) * e ^ {-x^2 / 2}" ) #?plotmath可以見到更多使用數(shù)學(xué)表達(dá)式的例子。 |
添加線條
當(dāng)進(jìn)行線性回歸時(shí),畫條擬合直線是個不錯的選擇。當(dāng)然有時(shí)畫水平線和垂直線顯示刻度也是可以的。
1
2
3
4
5
6
7
8
9
|
p <- ggplot(heightweight, aes(x=ageYear, y=heightIn, colour=sex)) + geom_point() #添加水平線和垂直線 p + geom_hline(yintercept=60) + geom_vline(xintercept=14) #添加擬合回歸線 p + geom_abline(intercept=37.4, slope=1.75) #我們也可以修改直線的類型 library(plyr) hw_means <- ddply(heightweight, "sex" , summarise, heightIn=mean(heightIn)) p + geom_hline(aes(yintercept=heightIn, colour=sex), data=hw_means,linetype= "dashed" , size=1) |
添加分割標(biāo)記
我們使用annotate(“segment”)畫分割線。
1
2
|
p <- ggplot(subset(climate, Source== "Berkeley" ), aes(x=Year, y=Anomaly10y)) +geom_line() p + annotate( "segment" , x=1950, xend=1980, y=-.25, yend=-.25) |
添加長方形陰影
使用annotate(“rect”)函數(shù)添加長方形陰影圖層。
1
2
|
p <- ggplot(subset(climate, Source== "Berkeley" ), aes(x=Year, y=Anomaly10y)) +geom_line() p + annotate( "rect" , xmin=1950, xmax=1980, ymin=-1, ymax=1, alpha=.1,fill= "blue" ) |
添加誤差線
誤差線常用于統(tǒng)計(jì)學(xué),以顯示數(shù)據(jù)潛在的誤差。使用geom_errorbar函數(shù),并需要映射ymin和ymax變量。
1
2
3
4
5
|
ce <- subset(cabbage_exp, Cultivar == "c39" ) ggplot(ce, aes(x=Date, y=Weight)) + geom_line(aes(group=1)) + geom_point(size=4) + geom_errorbar(aes(ymin=Weight-se, ymax=Weight+se), width=.2) |
給每個小平面增加注釋
我們根據(jù)數(shù)據(jù)類別畫了多個小平面,并想在每個小平面上標(biāo)上注釋。我們可以構(gòu)造一個數(shù)據(jù)框,并用geom_text()進(jìn)行構(gòu)造。
1
2
3
4
|
p <- ggplot(mpg, aes(x=displ, y=hwy)) + geom_point() + facet_grid(. ~ drv) #構(gòu)造注釋數(shù)據(jù)框 f_labels <- data.frame(drv = c( "4" , "f" , "r" ), label = c( "4wd" , "Front" , "Rear" )) p + geom_text(x=6, y=40, aes(label=label), data=f_labels) |
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/zx403413599/article/details/47008561