R 數(shù)據(jù)可視化 —— ggplot 柱狀圖/條形圖

前言

ggplot2 中有兩種繪制條形圖的函數(shù):geom_bar()geom_col()

geom_bar() 使條形的高度與每個組中的觀察值的數(shù)目成正比,或者如果設(shè)置了 weight 參數(shù),則為分組內(nèi)指定的所有權(quán)重變量值之和

如果你想直接使用條形圖的高度來表示數(shù)據(jù)中的值,可以使用 geom_col()

geom_bar() 默認(rèn)使用的統(tǒng)計變換方法是 count,而 geom_col() 使用 identity 不做變換。

示例

1 簡單條形圖

g <- ggplot(mpg, aes(class))
g + geom_bar()

使用 weight 參數(shù)來統(tǒng)計分組內(nèi) displ 變量值之和

g + geom_bar(aes(weight = displ))

繪制水平條形圖,有兩種方式,反轉(zhuǎn)坐標(biāo)軸或者將數(shù)據(jù)設(shè)置在 y

p1 <- ggplot(mpg) + geom_bar(aes(y = class))

p2 <- g + geom_bar() + coord_flip() 

plot_grid(p1, p2, labels = LETTERS[1:2], ncol = 2)

推薦使用翻轉(zhuǎn)坐標(biāo)軸的方式,因?yàn)橛行﹫D形是無法修改屬性映射的。

使用 geom_col 繪制條形圖

df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
ggplot(df, aes(trt, outcome)) +
  geom_col()

2. 設(shè)置顏色

p1 <- g + geom_bar(color = 'blue', fill='white')

p2 <- g + geom_bar(aes(fill=class))

p3 <- g + geom_bar(aes(colour=class), fill='white')

p4 <- g + geom_bar(aes(fill=class)) +
  scale_fill_manual(values = c("#8c510a", "#d8b365", "#f6e8c3", 
                               "#c7eae5", "#5ab4ac", "#01665e", "#af8dc3"))

plot_grid(p1, p2, p3, p4, labels = LETTERS[1:4], ncol = 2)

3. 分組條形圖

3.1 堆積條形圖

簡單堆積條形圖

g <- ggplot(mpg, aes(class))
g + geom_bar(aes(fill = drv))

翻轉(zhuǎn)堆積條形圖,并反轉(zhuǎn)堆積順序

ggplot(mpg, aes(y = class)) +
  geom_bar(aes(fill = drv), position = position_stack(reverse = TRUE)) +
  theme(legend.position = "top")

本來的堆積順序是,藍(lán)色在最下面,然后是綠色,最后是粉色,使用 position_stack 將該順序逆轉(zhuǎn)

那如何在堆疊塊之間設(shè)置空白間距呢?

我們可以先設(shè)置 lwd 參數(shù),增加外框線的寬度,然后將外框線的顏色設(shè)置成背景顏色,就可以達(dá)到目的了

那我不知道背景顏色怎么辦?也很簡單。

我們在主題章節(jié)介紹過 theme_get 函數(shù)可以獲取當(dāng)前主題,只要找到當(dāng)前主題的 panel.background 屬性,并找到對應(yīng)的填充色 fill 就可以知道啦。

> old<- theme_get()
> old$panel.background
List of 5
 $ fill         : chr "grey92"
 $ colour       : logi NA
 $ size         : NULL
 $ linetype     : NULL
 $ inherit.blank: logi TRUE
 - attr(*, "class")= chr [1:2] "element_rect" "element"

好了,現(xiàn)在知道了背景色為 grey92,那么我就可以繪制了

g <- ggplot(mpg, aes(class))
g + geom_bar(aes(fill = drv), lwd=1.5, colour='grey92')

當(dāng)然,你也可以指定分隔區(qū)的顏色,然后將背景色改為相應(yīng)的顏色就可以了

3.2 百分比條形圖

如果我們想知道每個分組中各部分的占比情況,可以設(shè)置 position = 'fill' 或者 position_fill() 函數(shù)來繪制百分比條形圖,例如

g + geom_bar(aes(fill = drv), 
                   position = 'fill')

3.3 并列條形圖

條形圖默認(rèn)會繪制堆積條形圖,我們可以使用 position_dodgeposition_dodge2 來繪制并列條形圖

position_dodge(width = NULL, preserve = c("total", "single"))

position_dodge2(
  width = NULL,
  preserve = c("total", "single"),
  padding = 0.1,
  reverse = FALSE
)

我們來看看這兩個函數(shù)的區(qū)別,當(dāng)不傳遞參數(shù)時,可以傳入字符串 dodgedodge2,分別代表這兩個函數(shù)

p1 <- g + geom_bar(aes(fill = drv), position = position_dodge())

p2 <- g + geom_bar(aes(fill = drv), position = position_dodge2())

plot_grid(p1, p2, labels = LETTERS[1:2], ncol = 2)

我們可以看到,dodge 同一組內(nèi)的柱子是靠近在一起的,而 dodge2 有空白間距。

由于默認(rèn)情況下,會保持分組的寬度一致,這就造成分類少的組內(nèi)柱子寬度更大,我們可以設(shè)置 preserve = 'single' 保持每個柱子的寬度是一樣的。

p1 <- g + geom_bar(aes(fill = drv), position = position_dodge(preserve = 'single'))

p2 <- g + geom_bar(aes(fill = drv), position = position_dodge2(preserve = 'single'))

plot_grid(p1, p2, labels = LETTERS[1:2], ncol = 2)

組內(nèi)柱子之間的間距怎么設(shè)置呢?這兩個函數(shù)的設(shè)置方式會有些差別

p1 <- g + geom_bar(aes(fill = drv), 
                   position = position_dodge(
                     preserve = 'single', width = 0.5))

p2 <- g + geom_bar(aes(fill = drv), 
                   position = position_dodge(
                     preserve = 'single', width = 1))

p3 <- g + geom_bar(aes(fill = drv), 
                   position = position_dodge2(
                     preserve = 'single', padding = 0.5))

p4 <- g + geom_bar(aes(fill = drv), 
                   position = position_dodge2(
                     preserve = 'single', padding = 1.2))

plot_grid(p1, p2, p3, p4, labels = LETTERS[1:4], ncol = 2)

我們可以看到,圖 A、B 設(shè)置的是分組總的寬度,寬度小于 1 會導(dǎo)致組內(nèi)柱子之間交疊,如果大于 1 會導(dǎo)致組間出現(xiàn)交疊

而圖 C、D 通過設(shè)置不同的 padding 值,會影響柱子的寬度,通過壓縮柱子的寬度來增加組內(nèi)間距。

3.3 設(shè)置條形圖誤差線

我們在并列條形圖的基礎(chǔ)上,繪制誤差線

mpg %>% 
  group_by(class, drv) %>% 
  summarise(count = n()) %>%
  ggplot(aes(class, count)) +
  geom_col(aes(fill=drv), position = position_dodge2(preserve = 'single')) +
  geom_errorbar(aes(ymin = count - 1, ymax = count + 1),
                position = position_dodge2(preserve = 'single', padding = 0.5))

因?yàn)槲覀冊诶L制誤差線時需要用到每個柱子的大小,所以在這里,我們先對數(shù)據(jù)進(jìn)行了匯總,然后使用 geom_col 繪制條形圖。

3.4 添加標(biāo)注

有時候,我們可能想知道條形圖的每個柱子的具體數(shù)值或占比情況,需要為每個柱子添加文本注釋信息

mpg %>% 
  group_by(class, drv) %>% 
  summarise(count = n()) %>%
  ggplot(aes(class, count)) +
  geom_col(aes(fill=drv), position = position_dodge2(preserve = 'single')) +
  geom_text(aes(label=count), 
            position = position_dodge2(width = 0.9, preserve = 'single'), 
            vjust = -0.2, hjust = 0.5)

我們使用 geom_text 添加標(biāo)簽注釋,有幾點(diǎn)需要注意

注意事項(xiàng)

geom_text 中設(shè)置的 position 信息需要與條形圖中的設(shè)置對應(yīng),即堆疊對應(yīng)堆疊,并列對應(yīng)并列,上面的例子是并列的方式。

柱子寬度需要一致,默認(rèn)為 0.9。同時,如果不設(shè)置 preserve = 'single',則寬度為整個分組的寬度。

vjust 設(shè)置為負(fù)數(shù)是將文本上移,hjust=0.5 為了水平對齊。

堆疊的例子

mpg %>% 
  group_by(class, drv) %>% 
  summarise(count = n()) %>%
  mutate(cumcount = cumsum(count)) %>%
  ggplot(aes(class, count)) +
  geom_col(aes(fill=drv), position = position_stack(reverse = TRUE)) +
  geom_text(aes(label = cumcount), 
            position = position_stack(), # 可以不設(shè)置該參數(shù)
            vjust = 0.5, hjust=0.5)

我們看到,標(biāo)簽都是放置在上面,那我想要把標(biāo)簽放中間怎么辦?

mpg %>% 
  group_by(class, drv) %>% 
  summarise(count = n()) %>%
  mutate(cumcount = cumsum(count), midcount = cumcount - count/2) %>%
  ggplot(aes(class, count)) +
  geom_col(aes(fill = drv), position = position_stack(reverse = TRUE)) +
  geom_text(aes(y = midcount, label = cumcount), hjust=0.5)

注意,我們不再為 geom_textposition 參數(shù)設(shè)置值,因?yàn)椴恍枰鶕?jù) y 的值進(jìn)行堆疊

4. 條形圖的變形

4.1 金字塔圖

df <- tibble(
  gene = factor(paste0("gene_", rep(1:16, 2)), levels = paste0("gene_", 16:1)),
  stat = c(seq(-10, -100, -10), seq(-90, -40, 10), seq(10, 100, 10), seq(90, 40, -10)),
  direct = rep(c("down", "up"), each=16)
)

ggplot(df, aes(gene, stat, fill = direct)) + 
  geom_col() +
  coord_flip() + 
  scale_y_continuous(breaks = seq(-100, 100, 20),
                     labels = c(seq(100, 0, -20), seq(20, 100, 20)))

4.2 偏差圖

df <- tibble(
  gene = factor(paste0("gene_", 1:20), levels = paste0("gene_", 20:1)),
  stat = c(seq(100, 10, -10), seq(-10, -100, -10)),
  direct = factor(rep(c("up", "down"), each=10), levels = c("up", "down"))
)

ggplot(df, aes(gene, stat, fill = direct)) + 
  geom_col() +
  coord_flip()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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