Bidirectional bar chart with positive labels on both sides ggplot2

こ雲淡風輕ζ 提交于 2020-01-02 05:11:10

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/38085590/bidirectional-bar-chart-with-positive-labels-on-both-sides-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!