Label data in column charts at "Dodge" position in R

Asked

Viewed 190 times

2

I am working with the following data frame:

library(tidyverse)

df<- data.frame(Ano=c(2017, 2018,2019,2020), Vagas=c(16, 14, 27, 32), Inscritos=c(70, 107,74,88), Aprovados=c(15,14,17, 12))

df

 Ano Vagas Inscritos Aprovados
1 2017    16        70        15
2 2018    14       107        14
3 2019    27        74        17
4 2020    32        88        12

I need to express this in the form of a column chart. Then convert to Tidy format as "Gather"

df2<-df %>% 
  gather(Condicao, n, c(Vagas:Aprovados))

Ano  Condicao   n
1  2017     Vagas  16
2  2018     Vagas  14
3  2019     Vagas  27
4  2020     Vagas  32
5  2017 Inscritos  70
6  2018 Inscritos 107
7  2019 Inscritos  74
8  2020 Inscritos  88
9  2017 Aprovados  15
10 2018 Aprovados  14
11 2019 Aprovados  17
12 2020 Aprovados  12

I would like to express the data in the form of columns side by side. So I use the geom_col() with the position dodge

df2 %>% 
  ggplot()+
  geom_col(aes(Ano, n, fill=Condicao), position="dodge")

grafico 1

I can create the Abels using the geom_label():

df2 %>% 
  ggplot(aes(Ano, Condicao, label = n))+
  geom_label(aes(Ano, n, label=n))

grafico 2

However, I can’t put them together properly.

I tried to:

df2 %>% 
  ggplot()+
  geom_col(aes(Ano, n, fill=Condicao), position="dodge")+
  geom_label(aes(Ano, n, label=n), position = "dodge")

inserir a descrição da imagem aqui

My intention is that the labels are ALIGNED to their respective columns:

2 answers

3


Can solve the problem with

  1. For aes(Ano, n) in the initial call to ggplot. This simplifies the geom_* since they share the values of the axes.
  2. Set the sliders grouping variable also at the beginning. It is then aes(Ano, n, group = Condicao).
  3. Use position_dodge(width = 1) in geom_label.

The final chart is as follows.

df2 %>% 
  ggplot(aes(Ano, n, group = Condicao)) +
  geom_col(aes(fill = Condicao), position = position_dodge()) +
  geom_label(aes(label = n), position = position_dodge(width = 1))

inserir a descrição da imagem aqui

  • Perfect. Exactly what I was looking for. Thank you Rui Barradas

0

You can use position = position_dodge(width = 1)

Code:

df2 %>% 
  ggplot(aes(Ano, n, fill=Condicao))+
  geom_bar(stat = 'identity', position="dodge") +
  geom_label(aes(Ano, n, label= n), position = position_dodge(width = 1))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.