Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of wider bars of a ggplot2 plot with geom_bar() in cases of count=0 [duplicate]

Here is my data.frame():

df <- data.frame(Round = rep(c("A", "B", "C" ),150), Group = rep(c("UP", "DOWN"),75),Task = rep(c("T1", "T2", "T3", "T4", "T5"),30), V2 = sample(c(0,1,2), 50, replace = T), V1 = sample(c(0,1,2), 50, replace = T))
dfmelt <- melt(df)

I am trying to plot a facet_grid like this:

b <- ggplot(data=dfmelt, aes(x=value, fill=variable))
b <- b + geom_bar(stat="count", position = "dodge", width = 0.9)
b <- b + facet_grid(Group ~ Task, scales = "free")

, which produces the following:

enter image description here

I want to get rid of the wider columns, such as V1 at the position 0 of T1-UP, V1 at the position 1 of T5-DOWN and V2 at the position 0 of T3-UP.

The problem occur when the count of one of my variables (let's say V1) in a given x position (0,1, or 2) is equal to 0 and the other variable (V2) is greater than 0. In this case, the V2 bar becomes wider to fill the whole x position.

I have tried this this and this solutions with no success. Is there a way to make the bars have a fixed width?

like image 669
Alcemir Santos Avatar asked Dec 19 '25 06:12

Alcemir Santos


1 Answers

One option is to implement the count manually outside ggplot, and fill missing data with NA with tidyr::complete and then do an identity bar plot:

library(dplyr); library(tidyr); library(ggplot2)
dfmelt_count <- dfmelt %>% 
        count(Group, Task, variable, value) %>% 
        complete(Group, Task, variable, value)

b <- ggplot(data=dfmelt_count, aes(x=value, y = n, fill=variable))
b <- b + geom_bar(stat="identity", position = "dodge", width = 0.9)
b <- b + facet_grid(Group ~ Task, scales = "free")
b

enter image description here

like image 110
Psidom Avatar answered Dec 21 '25 19:12

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!