1

Hello everybody I have a technical question for you plz.

my data :

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

And my plot :

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()

My plot works very well, but I want to add more information on it.

I would like to know if it would be possible to reveal the information of the column n on which there were "freq". Either below the bar (for example "107336/138666" above the "a") or on both sides of the bar in the plot.

Thanks for your help !

Humpelstielzchen
  • 6,126
  • 3
  • 14
  • 34
thomas leon
  • 153
  • 11

2 Answers2

2

One alternative is to just use position = position_fill(vjust = 0.5, reverse = T) in 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()

This way you can position your numbers freely inside the bars. position_fill(vjust = 0.9, reverse= T)for example would plot them higher.

enter image description here

The data:

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)
Humpelstielzchen
  • 6,126
  • 3
  • 14
  • 34
1

To scale the values of n to the plot coordinates I compute their magnitudes relative to the total n by groups of 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

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66