2018-10-17
閱讀量:
1614
給圖形添加輔助線?ggplot2來解決
橫軸為分類變量、縱軸為連續(xù)變量的數(shù)據(jù)圖表:
? dat <- read.table(header=TRUE, text='
? ?? ?? ?cond result
? ?? ?control? ???10
? ? treatment? ?11.5
? ? ')
library(ggplot2)
繪制橫跨整坐標(biāo)系的直線:
因?yàn)閥軸是連續(xù)的,所以在這里使用geom_hline, 在x軸是連續(xù)的情況下也可以使用geom_vline) 。
# 基本的條形圖
? ? bp <- ggplot(dat, aes(x=cond, y=result)) +
? ?? ???geom_bar(position=position_dodge(), stat="identity")
? ? bp
? ? # line 加入一個水平線
? ? bp + geom_hline(aes(yintercept=12))
? ? # 讓線變成紅色的虛線
? ? bp + geom_hline(aes(yintercept=12), colour="#990000", linetype="dashed")
為不同分類變量繪制獨(dú)立的輔助線:
為了給每個條形圖繪制不同的輔助線,我們需要用到geom_errorbar命令。我們的輔助線實(shí)際上是一個沒有高度的誤差帶,我們需要指定一系列y值來使它成為一條輔助線
? ? dat$hline <- c(9,12)
? ? dat
? ? #>? ?? ???cond result hline
? ? #> 1? ?control? ?10.0? ???9
? ? #> 2 treatment? ?11.5? ? 12
? ? # 需要重新設(shè)置bp,因?yàn)閿?shù)據(jù)已經(jīng)發(fā)生改變
? ? bp <- ggplot(dat, aes(x=cond, y=result)) +
? ?? ???geom_bar(position=position_dodge(), stat="identity")
# 為每個條形圖繪制單獨(dú)的線
? ? bp + geom_errorbar(aes(y=hline, ymax=hline, ymin=hline), colour="#AA0000")
? ? # 讓線短一點(diǎn)
? ? bp + geom_errorbar(width=0.5, aes(y=hline, ymax=hline, ymin=hline), colour="#AA0000")
? ? # 即使我們從另一個數(shù)據(jù)框中獲得hline的值,依然可以獲得相同的結(jié)果
? ? # 用hline重新定義數(shù)據(jù)框
? ? dat_hlines <- data.frame(cond=c("control","treatment"), hline=c(9,12))
? ? dat_hlines
? ? #>? ?? ???cond hline
? ? #> 1? ?control? ???9
? ? #> 2 treatment? ? 12
? ? # 根據(jù)dat繪制條形圖,根據(jù)dat_hlines繪制線
? ? bp + geom_errorbar(data=dat_hlines, aes(y=hline, ymax=hline, ymin=hline),
? ? dat$hline <- c(9,12)
? ? dat
? ? #>? ?? ???cond result hline
? ? #> 1? ?control? ?10.0? ???9
? ? #> 2 treatment? ?11.5? ? 12
? ? # 需要重新設(shè)置bp,因?yàn)閿?shù)據(jù)已經(jīng)發(fā)生改變
? ? bp <- ggplot(dat, aes(x=cond, y=result)) +
? ?? ???geom_bar(position=position_dodge(), stat="identity")
? ? # 為每個條形圖繪制單獨(dú)的線
? ? bp + geom_errorbar(aes(y=hline, ymax=hline, ymin=hline), colour="#AA0000")
? ? # 讓線短一點(diǎn)
? ? bp + geom_errorbar(width=0.5, aes(y=hline, ymax=hline, ymin=hline), colour="#AA0000")
? ? # 即使我們從另一個數(shù)據(jù)框中獲得hline的值,依然可以獲得相同的結(jié)果
? ? # 用hline重新定義數(shù)據(jù)框
? ? dat_hlines <- data.frame(cond=c("control","treatment"), hline=c(9,12))
? ? dat_hlines
? ? #>? ?? ???cond hline
? ? #> 1? ?control? ???9
? ? #> 2 treatment? ? 12
? ? # 根據(jù)dat繪制條形圖,根據(jù)dat_hlines繪制線
? ? bp + geom_errorbar(data=dat_hlines, aes(y=hline, ymax=hline, ymin=hline), colour="#AA0000")






評論(0)


暫無數(shù)據(jù)
推薦帖子
0條評論
0條評論
0條評論