ProgSnob ProgSnob - 4 years ago 152
R Question

ggplot2 make barplots of same width

I'm making two barplots using ggplot2 inside a shiny app. I need to make them of the same dimensions (width wise).

Two plots

I think the entire plot size, which includes the legend is the same for both plots. What I need to do is make the plot size same if the legend weren't being considered. I thought I could do this if I could make the bars in the plot thinner. =

EDIT: I took the suggestion to move the legend below, which fixed the issue. Now the bars of the plot look too thick.

plots with thick bars

Any way I could make them thinner?

Answer Source
library(ggplot2)
library(dplyr)    

mpg_filter <- mpg %>%
    filter(class %in% c("compact", "subcompact"))

mpg_filter2 <- mpg %>%
    filter(class %in% c("midsize", "suv"))

g <- ggplot(mpg_filter, aes(class))

g + geom_bar(aes(fill = drv), width = 0.5) +
    theme(legend.position = "bottom")

enter image description here

g2 <- ggplot(mpg_filter2, aes(class))

g2 + geom_bar(aes(fill = drv), width = 0.5) +
    theme(legend.position = "bottom")

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download