引言
光光展示數據對可視化來說,遠遠不夠。還有其他很多信息能夠幫助讀者解釋你的數據。除了標簽、坐標軸、圖例外,還能夠增加注釋,比如強調圖畫的某一區域,添加描述性文本等。
添加文本注釋
你可以在圖形中添加文本,增加可讀性。我們在annotate函數中設置text參數即可。
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" ) #由于設置的文本會覆蓋原來的圖中對應的位置,可以改變文本的透明度或者顏色 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) |
添加數學表達式注釋
我們也可以在圖形中注釋數學表達式。在annotate中增加parse=TRUE參數即可。
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可以見到更多使用數學表達式的例子。 |
添加線條
當進行線性回歸時,畫條擬合直線是個不錯的選擇。當然有時畫水平線和垂直線顯示刻度也是可以的。
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) |
添加分割標記
我們使用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”)函數添加長方形陰影圖層。
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" ) |
添加誤差線
誤差線常用于統計學,以顯示數據潛在的誤差。使用geom_errorbar函數,并需要映射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) |
給每個小平面增加注釋
我們根據數據類別畫了多個小平面,并想在每個小平面上標上注釋。我們可以構造一個數據框,并用geom_text()進行構造。
1
2
3
4
|
p <- ggplot(mpg, aes(x=displ, y=hwy)) + geom_point() + facet_grid(. ~ drv) #構造注釋數據框 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) |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/zx403413599/article/details/47008561