Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Misconfigured bar graph labels

I am working with the following syntax but the graphics labels appear as follows:
enter image description here

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading