Reputation: 735
I'm trying to use a stacked bar chart to display 2 sets of values in such a way that the values measuring the same domain across the 2 groups travel in opposite directions similar to a stacked negative bar chart. I have "hijacked" a stacked bar chart to do this by setting one groups values to be negative. This gives me the image that I want; however, I want to remove the negatives from the bottom set of stacked bars. Is there a way to do this? Also, I was wondering why the width= option in the bar geom does not adjust the width of the bars? When I add the width=0.5 for example as an option in the geom_bar specification I get the error:
Warning message:
Stacking not well defined when ymin != 0
Anyhow, thanks in advance for any help you can offer. My example code is as follows:
test <- structure(list(Mode = structure(c(2L, 1L, 3L, 2L, 1L, 3L), .Label = c("Air","Land", "Sea"), class = "factor"), Side = structure(c(2L, 2L,2L, 1L, 1L, 1L), .Label = c("Allies", "Axis"), class = "factor"),Value = c(72L, 12L, 16L, -84L, -12L, -22L)), .Names = c("Mode", "Side", "Value"), class = "data.frame", row.names = c(NA, -6L))
p <- ggplot(test, aes(x= Mode, y=Value, fill= Mode)) + geom_bar(color = "black", stat="identity", data=subset(test, Side == "Axis")) + geom_bar(color = "black", stat="identity", data=subset(test, Side == "Allies")) + scale_fill_brewer(type = "seq", palette = 1)+ guides(fill=FALSE) + scale_y_continuous(breaks=seq(-100, 100,10))
Upvotes: 1
Views: 620
Reputation: 173517
I thought that the width issue in geom_bar
had been resolved, but for some reason I'm still seeing it in 0.9.2.1. I may be missing something on that front, but the old fix of setting the width inside aes()
still works for me.
Also, I think you meant that you wanted the y axis labels below 0 to not be negative numbers, but your question wasn't totally clear on that. If I'm right, then this is probably what you're after:
abs_format <- function(){
function(x){
abs(x)
}
}
p <- ggplot(test, aes(x= Mode, y=Value, fill= Mode,width = 0.1)) +
geom_bar(color = "black", stat="identity", data=subset(test, Side == "Axis")) +
geom_bar(color = "black", stat="identity", data=subset(test, Side == "Allies")) +
scale_fill_brewer(type = "seq", palette = 1) +
guides(fill=FALSE) +
scale_y_continuous(breaks=seq(-100, 100,10),labels = abs_format())
Also, I should add that the message you get about stacking not being well defined is not an error. It's simply a warning, and means that you should be watchful. ggplot will sometimes have a difficult time figuring out how to stack things when using negative values. Things will usually work, it's just warning you to be alert for dragons.
Upvotes: 2