Julie Button
Julie Button

Reputation: 1

Creating side by side bar plot for layered bar plots

I have the following code

ggplot() +
  geom_bar(data = AgePlot, aes(x = FamSize, y = Page1), fill= "black", color = "black", alpha = .5, stat = "summary", fun = mean) +
  geom_bar(data = AgePlot, aes(x = FamSize, y = A2age1), fill= "darkblue", color = "darkblue", alpha = .2, stat = "summary", fun = mean) +
  scale_x_discrete(limits = 2:4, labels = c("2 Children", "3 Children", "4 or More Children")) +
  labs (x = "Family Size", y = "Mean Age of Adults") +
  ggtitle("Mean Age of Parent (Black) and Second Adult (Blue) Based on Family Size")

In order to run the mean function on the data for my y axis I need to put all of the data, and aes in the geom_bar function. When I then try to use the position and "dodge" it does not move the bars side by side. Instead they remain on top of each other. The information is all still displayed by altering the alpha you can see the two plots on top of each other.

However, for display purposes I would like the two bars to be side by side.

Upvotes: 0

Views: 95

Answers (1)

Jon Spring
Jon Spring

Reputation: 66490

Here are two approaches using the mtcars dataset:

Option 1, using some janky adjustments in the plot to make it look dodged:

ggplot() +
  geom_bar(data = mtcars, aes(x = gear+0.2, y = mpg), width = 0.4,
           fill= "black", color = "black", alpha = .5, stat = "summary", fun = mean) +
  geom_bar(data = mtcars, aes(x = gear-0.2, y = hp), width = 0.4, 
           fill= "darkblue", color = "darkblue", alpha = .2, stat = "summary", fun = mean) +
  scale_x_discrete(limits = 3:5, labels = c("2 Children", "3 Children", "4 or More Children")) +
  labs (x = "Family Size", y = "Mean Age of Adults") +
  ggtitle("Mean Age of Parent (Black) and Second Adult (Blue) Based on Family Size")

enter image description here

Option 2, calculate the numbers before ggplot2 in longer format, and then use normal dodging:

mtcars %>%
  group_by(gear) %>%
  summarize(mpg = mean(mpg),
            hp = mean(hp)) %>%
  pivot_longer(-gear) %>%
  ggplot(aes(gear, value, fill = name)) +
  geom_col(position = "dodge", alpha = 0.3, color = "darkblue") +
  scale_x_discrete(limits = 3:5, labels = c("2 Children", "3 Children", "4 or More Children")) +
  scale_fill_manual(values = c("mpg" = "black", "hp" = "darkblue"))

enter image description here

Upvotes: 1

Related Questions