Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bidirectional bar chart with positive labels on both sides ggplot2

I'm try to create a bidirectional bar chart in ggplot where axis labels and data labels both above and below the axis are positive. So for example, if your data was:

myData <- data.frame(category = c("yes", "yes", "no", "no"), month = c('Jan', 'Feb', 'Jan', 'Feb'), values = c(6, 5, 4, 3))

I'd want two columns, one for January and one for February, where the 'yes' values appeared pin bars pointing up with positive axis and data labels, and the 'no' values pointing down, also with positive axis and data labels. There would be a '0' value bar in between them. Is this possible in ggplots, and if so, how can it be accomplished? Thanks.

like image 379
Tom.Rampley Avatar asked Jun 28 '16 20:06

Tom.Rampley


1 Answers

Are you looking for something like this? We can pass the "no"s as negatives, but have ggplot display them as positive values. Same thing for the labels.

myData$values2 <- ifelse(myData$category == "no", -1 * myData$values, myData$values)

library(ggplot2)
ggplot(data = myData) + geom_bar(aes(x=month,y=values2,fill=category),stat="identity",position="identity") +
                        geom_text(aes(x=month,y=values2,label=abs(values2)),vjust = ifelse(myData$values2 >= 0, 0, 1)) +
                        scale_y_continuous(labels=abs)

enter image description here

like image 86
Mike H. Avatar answered Sep 29 '22 01:09

Mike H.