1

Have already tried this link but it fails to work, moreover this question was asked 5 years ago so I hope there is a better way around than this lengthy code.

How to make the width of bars and spaces between them fixed for several barplots using ggplot, having different number of bars on each plot?

#with 10 bins
data <- data.frame(x=1:10,y=runif(10))
library(ggplot2)
ggplot(data, aes(x,y)) + geom_bar(stat="identity")

#with 3 bins
ggplot(data[1:3,], aes(x,y)) + geom_bar(stat="identity")

Adding width=1 to geom_bar(...) doesn't help as well. I need the second plot automatically to have less width and the same bar width and spaces as the first one.

Z.Lin
  • 28,055
  • 6
  • 54
  • 94

1 Answers1

1

One solution would be to adjust the coordinates to match:

ggplot(data[1:3,], aes(x,y)) + geom_bar(stat="identity") +
scale_x_continuous(limits = c(0.5,10)) # This is approximate but pretty close.
#
# For an exact match, you can go into the ggplot_build object and
# extract [["layout"]][["panel_params"]][[1]][["x.range"]]
# You could then use the exact values:
# scale_x_continuous(limits = c(0.055,10.945), expand = c(0,0))

enter image description here

Another would be to combine the bars into one plot, and then use facets to show the data on the same scale.

library(dplyr)
data2 <- 
  data %>% mutate(plot = "A") %>%
  bind_rows(
    data[1:3,] %>% mutate(plot = "B")
  )

(a <- ggplot(data2, aes(x,y)) + geom_bar(stat="identity") +
  facet_grid(~plot)
)

If you want to use this with plotly, you could then use plotly::ggplotly(a). enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • I tried above but facet_share does not work with ggplotly. Can anyone please suggest a way to eliminate most of the white spaces in my original question above ? – Manvendra Shrimal Dec 11 '18 at 07:52
  • `facet_wrap` and `facet_grid` do work with `ggplotly` in my experience. Please see updated answer. (BTW it would be helpful to mention `ggplotly` in your question if it is one of your requirements.) – Jon Spring Dec 11 '18 at 18:18