双向条形图,两边都有正面标签ggplot2

时间:2022-01-30 15:02:22

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:

我尝试在ggplot中创建一个双向条形图,其中轴标签和轴上方和下方的数据标签都是正的。例如,如果您的数据是:

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.

我想要两列,一个用于一月,一个用于二月,其中“是”值显示针杆指向正轴和数据标签,“否”值指向下,也带有正轴和数据标签。它们之间会有一个“0”值栏。这是可能的ggplots,如果是这样,它怎么能完成?谢谢。

1 个解决方案

#1


5  

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.

你在找这样的东西吗?我们可以将“否”作为底片传递,但让ggplot将它们显示为正值。标签也一样。

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)

双向条形图,两边都有正面标签ggplot2

#1


5  

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.

你在找这样的东西吗?我们可以将“否”作为底片传递,但让ggplot将它们显示为正值。标签也一样。

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)

双向条形图,两边都有正面标签ggplot2