Manvendra Shrimal
Manvendra Shrimal

Reputation: 53

Keeping the width constant in ggplot in R

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.

Upvotes: 1

Views: 127

Answers (1)

Jon Spring
Jon Spring

Reputation: 66970

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

Upvotes: 1

Related Questions