Show Data Labels in Column Chart in R (ggplot2)

Asked

Viewed 2,242 times

1

I’m a beginner in R and I’m trying to create a bar chart and I can’t display the data labels on each bar.

Follow link to the used data frame: https://drive.google.com/open?id=1P6RLgzOgnZisI4BUYFHsEZ3b-Ca4XXd-uEg7t_Vasi

I’m using the following code:

library(ggplot2)
library(readxl)

Vendas <- read_excel("D:/BDados.xlsx", sheet = "Plan1")

ggplot(Vendas)+
  stat_count(aes(ID_LOC)) +
  labs(title = "Vendas", x="ID_Regioes", y="Total") +
  theme_grey(base_size = 10)

My chart is getting like this:

Gráfico

  • Which one of the columns is the label? And you want it to be where, in a coma of the columns?

  • I believe that the AP calls a label the numerical value corresponding to the height of the bars. That is, he wishes that, above column A, a number approximately equal to 375; above column B, almost 1200, and so on.

  • That’s right! I need data labels for all columns to appear!

2 answers

4

You can use both geom_text()Qunate geom_label(). See the example using geom_text(). First I will clear a dataframe to use as an example.

library(ggplot2)
vendas = data.frame(total =c(1150, 900, 850, 530, 600),
                    ID_Regioes = c("A", "B", "C", "D", "E"))

vendas %>% ggplot(aes(x = ID_Regioes, y = total)) +
  geom_col() +
  scale_y_continuous(limits = c(0, 1300))+
  geom_text(aes(label = total), 
            vjust = -1) +
  labs(title = "Vendas", x="ID_Regioes", y="total") +
  theme_grey(base_size = 10)

inserir a descrição da imagem aqui

I used scale_y_continuous(limits = c(0, 1300)) to adjust the limits of the Y-axis. Also test how geom_label() to see the difference. I hope I’ve helped.

1


This solution uses the package dplyr to pre-process the data.

library(ggplot2)
library(dplyr)

Vendas %>%
  group_by(ID_LOC) %>%
  summarise(n = n()) %>%
  ggplot(aes(ID_LOC, n, label = n)) +
  geom_col() +
  geom_text(aes(y = n), vjust = -0.1) +
  labs(title = "Vendas", x = "ID_Regioes", y = "Total") +
  theme_grey(base_size = 10)

inserir a descrição da imagem aqui

Browser other questions tagged

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