使用ggplot在堆叠的条形图中添加计数标签

时间:2019-07-01 08:36:49

标签: r ggplot2 bar-chart

大家好,我对您有一个技术问题。

我的数据:

Gel_J0 un_sucess      n  Freq
   <fct>  <fct>      <int> <dbl>
 1 a      sucess    107336  43.6
 2 a      unsucess  138666  56.4
 3 b      sucess      9558  46.0
 4 b      unsucess   11210  54.0
 5 c      sucess      4995  45.2
 6 c      unsucess    6060  54.8
 7 d      sucess      2193  44.9
 8 d      unsucess    2687  55.1
 9 e      sucess       991  44.2
10 e      unsucess    1251  55.8

我的情节:

ggplot(data= data , aes(x= Gel_J0, y=Freq, fill=un_sucess)) +
geom_bar(stat = "identity", position = position_fill(reverse = TRUE)) +
    scale_fill_brewer(palette = "Paired", direction = -1) +
  theme_minimal()

我的剧情效果很好,但是我想添加更多信息。

我想知道是否有可能显示“频率”列n的信息。在条形图下方(例如,在“ a”上方的“ 107336/138666”)或图形中条形图的两侧。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

一种选择是仅在position = position_fill(vjust = 0.5, reverse = T)中使用geom_text()

library(tidyverse)
ggplot(data= df,aes(x= Gel_J0, y=Freq, fill=un_sucess)) +
  geom_bar(stat = "identity", position = position_fill(reverse = TRUE)) +
  geom_text(aes(label = n), position = position_fill(vjust = 0.5, reverse= T)) +
  scale_fill_brewer(palette = "Paired", direction = -1) +
  theme_minimal()

这样,您可以将数字自由放置在条形图中。 例如,position_fill(vjust = 0.9, reverse= T)会将它们绘制得更高。

enter image description here

数据:

df <- read.table(text = "
Gel_J0 un_sucess      n  Freq
1 a      sucess    107336  43.6
2 a      unsucess  138666  56.4
3 b      sucess      9558  46.0
4 b      unsucess   11210  54.0
5 c      sucess      4995  45.2
6 c      unsucess    6060  54.8
7 d      sucess      2193  44.9
8 d      unsucess    2687  55.1
9 e      sucess       991  44.2
10 e      unsucess    1251  55.8", header = T)

答案 1 :(得分:1)

要将n的值缩放到绘图坐标,我按n组计算它们相对于总Gel_J0的大小。

library(tidyverse)

data %>% group_by(Gel_J0) %>% mutate(p = n/sum(n)) %>%
  ggplot(aes(x = Gel_J0, y=Freq, fill=un_sucess)) +
  geom_bar(stat = "identity", position = position_fill(reverse = TRUE)) +
  scale_fill_brewer(palette = "Paired", direction = -1) +
  geom_text(aes(y = p, label = n, vjust = 2)) +
  theme_minimal()

enter image description here

相关问题