条形图的边界被条形图所覆盖。

时间:2022-06-15 15:02:45

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

条形图的边界被条形图所覆盖。

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.

我试着修改它,在填充= NA的木条后画出木条,这确实画出了木条的顶端,但不是在正确的位置。

    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

条形图的边界被条形图所覆盖。

Any ideas how to fix this?

有办法解决这个问题吗?

1 个解决方案

#1


2  

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

将Var1映射到组美学,使其在第二个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()

#1


2  

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

将Var1映射到组美学,使其在第二个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()