sler
sler

Reputation: 75

is there a way to reduce the gap between bar in ggplot2

I have a dataset like below

mydata <- data.frame(size=c("0-1","1-2","2-4","4-8","8-16","16-32","0-1","1-2","2-4","4-8","8-16","16-32"),
                     x=c(0.7,1.41,2.83,5.65,11.31,22.63,0.7,1.41,2.83,5.65,11.31,22.63),
                     y=c(0.05,0.3,0.15,0.25,0.2,0.05,0.05,0.2,0.25,0.3,0.15,0.05),
                     z=c("A","A","A","A","A","A","B","B","B","B","B","B"))

I want to make a stacked bar plot on a log scale as you see they are equal spaced. With the code below, I get the desired plot but with gap between the bar. How can I get the plot without this gap? I tried width=1 but then the x-axis goes beyond the given value.

ggplot(mydata, aes(x=x, y=y, fill=z)) + 
  geom_bar(stat='identity')+
  scale_x_log10()+
  scale_y_continuous()

Upvotes: 1

Views: 109

Answers (1)

TarJae
TarJae

Reputation: 79246

We could do it this way:

transform x in the dataframe before plotting to log10 then transform to class factor and set width 1:

mydata %>% 
  mutate(log10_x = round(log10(x),2),
         log10_x = as.factor(log10_x)) %>% 
  ggplot(aes(x= log10_x, y=y, fill=z)) +
           geom_col(width = 1)

enter image description here

Upvotes: 1

Related Questions