Reputation: 429
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:
When I want it to look like this:
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
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
Upvotes: 1