Paul Murray
Paul Murray

Reputation: 429

Invert Subplot Across X Axis in R Barchart

I'm trying to plot two halves of a dataset in a bar chart in R. What I want is for the datasets to be on opposite sides of the x-axis rather than layered on top of each other on the same side of the axis. My chart currently looks like this: enter image description here

When I want it to look like this: enter image description here

Here is my code right now:

p <- ggplot(df_customer, aes(factor(income), percent_travel, fill = gender)) + 
    geom_bar(stat="identity", data = subset(df_customer, gender == "F")) +
    geom_bar(stat="identity", data = subset(df_customer, gender == "M"), stackdir = "down") +
    scale_x_discrete(name = "Annual Income ($1000's)", breaks=seq(-10, 100, 10)) +
    scale_y_discrete(name = "Income Spent on Travel (%)", breaks=seq(0, 8, 2))
p

I tried to use stackdir but I think that's an attribute that only works for scatter plots. I might be able to get the result I want by making all the values in one of the datasets negative but it doesn't seem like an ideal solution.

Also, any idea why my y-axis scale isn't showing up?

Thanks!

Upvotes: 0

Views: 371

Answers (1)

Andrew Gustar
Andrew Gustar

Reputation: 18425

Here is one way to do it. Note that y is a continuous scale, not discrete.

p <- ggplot(df_customer, aes(x = as.factor(income), 
                             y = percent_travel * ((-1)^(gender == "F")), 
                             fill = gender)) + 
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "Annual Income ($1000's)") +
  scale_y_continuous(name = "Income Spent on Travel (%)", breaks=seq(-8, 8, 2))
p

enter image description here

Upvotes: 1

Related Questions