waealu
waealu

Reputation: 331

R - Clustered bar chart with varying widths in ggplot

I have a dataset with subgroups and I want to display 2 pieces of data in a bar chart (one using the height of the bar and one using the bar width).

I would call it a clustered bar chart with varying bar widths.

This is what I have so far:

library(ggplot2)

df <- data.frame(Year = c('2010',rep('2011', 2), rep('2012', 3), rep('2013', 4)),
                 Subyear = c('2010','2010','2011','2010','2011','2012','2010','2011','2012','2013'),
                 Size = c(100, 50, 150, 25, 45, 140, 10, 25, 50, 200),
                 Pct = runif(10, 20, 150) / 100)

ggplot(df, aes(x = Year, y = Pct, fill = Subyear, width = Size/500)) +
geom_bar(stat = "identity", position = "dodge")

This is the plot I get. It's close, but I want the subyear bars displayed as clustered bars (instead of overlapping).

Thanks for the help!

enter image description here

Upvotes: 3

Views: 959

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50678

Provided I understood you correctly, you can use position = "dodge2"

ggplot(df, aes(x = Year, y = Pct, fill = Subyear, width = Size/500)) +
    geom_col(position = "dodge2")

enter image description here

From the ggplot2::position_dodge reference (bold face mine):

Dodging preserves the vertical position of an geom while adjusting the horizontal position. position_dodge2 is a special case of position_dodge for arranging box plots, which can have variable widths. position_dodge2 also works with bars and rectangles.

Upvotes: 3

Related Questions