R 數(shù)據(jù)可視化 —— ggplot 誤差圖和邊際線

誤差圖

設(shè)置垂直間隔的方式有很多,每種方式對(duì)應(yīng)于一種圖形,包括:

  • geom_crossbar
  • geom_errorbar
  • geom_linerange
  • geom_pointrange

示例

對(duì)于如下數(shù)據(jù)

df <- data.frame(
  trt = factor(c(1, 1, 2, 2)),
  resp = c(1, 5, 3, 4),
  group = factor(c(1, 2, 1, 2)),
  upper = c(1.1, 5.3, 3.3, 4.2),
  lower = c(0.8, 4.6, 2.4, 3.6)
)

> df
  trt resp group upper lower
1   1    1     1   1.1   0.8
2   1    5     2   5.3   4.6
3   2    3     1   3.3   2.4
4   2    4     2   4.2   3.6

繪制范圍線條

p <- ggplot(df, aes(trt, resp, colour = group))
p + geom_linerange(aes(ymin = lower, ymax = upper))

設(shè)置點(diǎn)范圍

p + geom_pointrange(aes(ymin = lower, ymax = upper))

設(shè)置矩形范圍

p + geom_crossbar(aes(ymin = lower, ymax = upper), width = 0.2)

誤差線,我們之前已經(jīng)畫過了

p + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.1)

上面這些例子都是豎直方向上的,要繪制水平方向,只要將軸翻轉(zhuǎn)一下即可

p + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.1) +
  coord_flip()

為分組添加連接線

p + geom_line(aes(group = group)) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.1)

為條形圖添加誤差線

ggplot(df, aes(trt, resp, fill = group)) +
  geom_col(position = "dodge2") +
  geom_errorbar(
    aes(ymin = lower, ymax = upper),
    position = position_dodge2(width = 0.2, padding = 0.8)
  ) +
  coord_flip()

邊際分布

邊際分布圖用于在 2D 圖形中,繪制數(shù)據(jù)在 XY 軸的映射,適用于較小的數(shù)據(jù)集

默認(rèn)情況下,線條長(zhǎng)度為整個(gè)圖形的 3%,而數(shù)據(jù)繪制區(qū)域距離兩端的間隙為 5%。因此,默認(rèn)情況下邊際分布不會(huì)和數(shù)據(jù)重疊

示例

例如,對(duì)于如下分布

p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point()
p

我們可以添加數(shù)據(jù)的邊際分布

p + geom_rug()

能夠很容易的觀察出數(shù)據(jù)在某一維度的分布情況

我們也可以只繪制一個(gè)維度

p + geom_rug(sides = 'l')

通過設(shè)置 sides 參數(shù),該參數(shù)接受 t(top)、r(right) b(bottom) l(left) 的任意組合

從上面的圖可以看出,許多點(diǎn)映射到坐標(biāo)軸后是重疊在一起的,我們可以設(shè)置 position 參數(shù),盡量避免重疊情況

ggplot(mpg, aes(displ, cty)) +
  geom_jitter() +
  geom_rug(alpha = 1/2, position = "jitter")

讓線條朝外

p + geom_rug(outside = TRUE) +
  coord_cartesian(clip = "off")

與軸標(biāo)簽重疊了,將它們放到上面和右邊去。同時(shí),記得設(shè)置一下邊距,不然線條會(huì)被遮蓋

p + geom_rug(outside = TRUE, sides = 'tr') +
  coord_cartesian(clip = "off") +
  theme(plot.margin = margin(1, 1, 1, 1, "cm"))

如果要設(shè)置線條的長(zhǎng)度,記得同時(shí)修改數(shù)據(jù)區(qū)域與軸線的間距,避免與數(shù)據(jù)點(diǎn)重疊

p + geom_rug(length = unit(0.05, "npc")) +
   scale_y_continuous(expand = c(0.1, 0.1))

設(shè)置顏色與線條類型與大小

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  geom_rug(sides = 'l', colour = "#a65628", linetype = 2, size = 2) +
  geom_rug(sides = 'b', colour = "#377eb8", linetype = 5, size = 2.5)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容