Martin
Martin

Reputation: 307

Borders in stacked bar chart are being overplotted by the bars

I’m trying to make a stacked bar chart, where some of the bars get a black boarder and others don’t. To accomplish this, I set the color depending on the variable choose. When it’s true, the boarder is black, otherwise it’s transparent.

The Problem: When the first bar has a boarder, the right edge of the boarder gets overplotted by the second bar.

Here is my code and an image of the problem:

    #Sample Data
    Var1 <- rep(c("A1","A2"),4)
    Var2 <- c("Q1","Q1","Q2","Q2","Q3","Q3","Q4","Q4")
    Freq <- c(4,2,6,2,6,4,9,3)
    choose <- c(F,F,T,F,F,T,F,T)

    df <- as.data.frame(cbind(Var1,Var2, Freq,choose))


    g<- ggplot(df, aes(x=factor(Var2), y=Freq))+ 
      geom_bar(stat="identity", aes(fill = Var1, color = choose), size = 3) +
      scale_color_manual(values = c('FALSE' = 'transparent', 'TRUE' = 'black'))+
      coord_flip()

    g

Problem

I tried to fix it, by drawing the boarder after the bars with fill = NA, this does draw the boarders on top of the bars, but not at the right position.

    g<- ggplot(df, aes(x=factor(Var2), y=Freq))+ 
      scale_color_manual(values = c('FALSE' = 'transparent', 'TRUE' = 'black'))+
      geom_bar(stat="identity", aes(fill = Var1))+
      geom_bar(stat="identity", aes(color = choose),  fill = NA, size = 3)+
      coord_flip()

    g

Problem fix

Any ideas how to fix this?

Upvotes: 3

Views: 635

Answers (1)

aosmith
aosmith

Reputation: 36086

Map Var1 to the group aesthetic to get things stacked in your second geom_bar.

ggplot(df, aes(x=factor(Var2), y=Freq))+ 
    scale_color_manual(values = c('FALSE' = 'transparent', 'TRUE' = 'black'))+
    geom_bar(stat="identity", aes(fill = Var1))+
    geom_bar(stat="identity", aes(color = choose, group = Var1),  fill = NA, size = 3)+
    coord_flip()

Upvotes: 2

Related Questions