Search code examples
rggplot2bar-chartgeom-bargeom-text

Geom_bar compared with geom_text with two discrete variables


I am having two discrete variables (Extract:)

Mitarbeiter <- c('0-10', '10-50', '50-250', '250+','10-50', '50-250', '250+', '250+', '0-10')
Behandlung <- c('E-Mail', 'Telefon', 'TV',  'Email', 'Telefon', 'TV', 'Email', 'TV', 'TV') 
Daten <- data.frame(Mitarbeiter, Behandlung)

I already created a graph with geom_bar:

ggplot(Daten, aes(x = Mitarbeiter, fill = Behandlung)) +
  geom_bar(position="fill")+
  labs(title="IT-Sicherheitsumgang nach Mitarbeiteranzahl", x="Mitarbeiter", y="prozentualer Anteil") + # legends
  coord_flip()+
  scale_fill_manual(values=c("snow2","lightblue","skyblue3","#2A5DA3","darkblue"))+
  theme_bw()

Now, I would like to add the number of TVs, phones and Emails for a specific Group of Mitarbeiter to the plot. I tried to use different versions of geom_text but it is not working for me.

Do you know a solution? Thank you!


Solution

  • You can try this:

    library(dplyr)
    library(ggplot2)
    
    Mitarbeiter <- c('0-10', '10-50', '50-250', '250+','10-50', '50-250', '250+', '250+', '0-10')
    Behandlung <- c('Email', 'Telefon', 'TV',  'Email', 'Telefon', 'TV', 'Email', 'TV', 'TV') 
    Daten <- data.frame(Mitarbeiter, Behandlung)
    
    ggp <- Daten %>% count(Mitarbeiter,Behandlung)
    
    ggplot(ggp,aes(Mitarbeiter,n,fill=Behandlung)) +
      geom_bar(stat="identity",position = "fill") + 
      geom_text(aes(label=n),position = position_fill(vjust = 0.5))+
      scale_fill_manual(values=c("snow2","lightblue","skyblue3","#2A5DA3","darkblue"))+
      labs(title="IT-Sicherheitsumgang nach Mitarbeiteranzahl", x="Mitarbeiter", y="prozentualer Anteil") +
      coord_flip()+theme_bw()
    

    enter image description here