Christine Blume
Christine Blume

Reputation: 527

ggplot2 barplot: decrease width and spacing at the same time

I would like to make a barplot using ggplot. Ideally, my bars should be fine and there should not be a space between them. Any ideas how I can achieve that?

data_hrs <- rnorm(n=513, m=20, sd=1) 
hours <- 528
days <- ceiling(hours/24)
days_hours <- days*24

data_hrs[days_hours] <- NA ## padding with NA to reach full no of days
hours <- length(data_hrs)
hours_count <- seq(1:24)
hours_count <- rep(hours_count,days)

day_count <- NA ## counts the days
for (t in 1:days){
  day_count[((t-1)*24+1):(t*24)] <- rep(t,24)
}

df_plot <- data.frame(day_count, hours_count, data_hrs)

print(ggplot(df_plot, aes(x=hours_count, y = data_hrs))+ 
      geom_bar(stat="identity", width = 0.1, position = position_dodge(width = 0.5))+
      theme_bw()+
      facet_grid(day_count ~ .)+
      scale_x_discrete(limits = c(seq(1:24)))+
      theme(axis.text.x = element_text(angle = 90, hjust = 1)))

This gives me the following (using my data): enter image description here

Upvotes: 0

Views: 433

Answers (1)

Thierry
Thierry

Reputation: 18487

Use width = 1 to remove the space between the bars. Create a narrow plot if you want fine bars. A wide graph is not compatible with fine bars without space between the bars.

ggplot(df_plot, aes(x=hours_count, y = data_hrs))+ 
  geom_bar(stat="identity", width = 1)+
  theme_bw()+
  facet_grid(day_count ~ .)+
  scale_x_discrete(limits = c(seq(1:24)))+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

Upvotes: 1

Related Questions