I am working with the following syntax but the graphics labels appear as follows:

The code used is the following
library(readxl)
base <- read_excel("F:\\Users\\YEFERSON_DP\\Desktop\\Procesamiento\\Embajada 3\\Embajada\\Embajada\\TOM1\\Deliverables\\Output\\Embajada_DP_FINAL.xlsx")
# Visualiza los datos
head(data)
# Calcular el porcentaje total
total_weight <- sum(base$weight)
base$Porcentaje <- (base$weight / total_weight) * 100
# Cargar la biblioteca ggplot2
library(ggplot2)
# Crear un gráfico de barras horizontales con etiquetas de porcentaje
ggplot(base, aes(x = Porcentaje, y = reorder(SEL, Porcentaje), label = paste0(round(Porcentaje, 2), "%"))) +
geom_bar(stat = "identity") +
labs(x = "Porcentaje Total", y = "SEL") +
geom_text(hjust = 0.5, size = 4)
I will also share the data if it is necessary to determine the problem. text
I would like to be able to obtain the data labels correctly, any ideas?
>Solution :
The problem is that your bars are made up of lots of little bars stacked on top of each other. All of your percentage labels are the percentages for each row in your data frame. Since they are not stacked or summarized, you get hundreds of text labels of a fraction of a percent overplotted on each other.
The most sensible way to fix this is to summarize your data ahead of plotting it:
library(tidyverse)
base %>%
group_by(SEL) %>%
summarize(weight = sum(weight)) %>%
mutate(Porcentaje = weight / sum(weight),
SEL = reorder(SEL, Porcentaje)) %>%
ggplot(aes(Porcentaje, SEL)) +
geom_col(fill = 'lightgray', color = 'black') +
geom_text(aes(x = Porcentaje/2, label = scales::percent(Porcentaje)),
size = 5) +
scale_x_continuous(labels = scales::percent) +
theme_minimal(base_size = 16)
