感谢您提前提供的帮助。我对 R 比较陌生,正在研究使用 ggplot2 创建双向条形图。
p3 <- ggplot(online_offline,aes(x=Year,y=Percentage, fill=Online_Offline))+
geom_bar(stat="identity", position="identity")+
scale_y_continuous(breaks = seq(-max(online_offline$Percentage), max(online_offline$Percentage), 10))+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 15))+
coord_flip()
p3
这是我正在使用的代码,这是我得到的结果。 enter image description here
我希望它看起来像 this 。有人可以帮我吗?
我使用的数据是: Data
最佳答案
问题是您必须更改其中一个类别的值的符号。这可以实现,例如通过将 ifelse(on_off == "Online", Percentage, -Percentage)
映射到 y
上。此外,要设置轴的范围,您必须使用 limits
而不是 breaks
:
online_offline <- structure(list(Year = c(2015L, 2015L, 2016L, 2016L, 2017L, 2017L,
2018L, 2018L, 2019L, 2019L, 2020L, 2020L), Percentage = c(19.5,
73.6, 19.3, 72.7, 21.8, 69.3, 26.1, 64.7, 28.6, 62.9, 61.4, 36.8
), on_off = c("Online", "Offline", "Online", "Offline", "Online",
"Offline", "Online", "Offline", "Online", "Offline", "Online",
"Offline")), row.names = c(NA, -12L), class = "data.frame")
library(ggplot2)
ggplot(online_offline,aes(x=Year, y = ifelse(on_off == "Online", Percentage, -Percentage), fill=on_off))+
geom_bar(stat="identity", position="identity")+
scale_y_continuous(limits = c(-max(online_offline$Percentage), max(online_offline$Percentage))) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 15))+
coord_flip()
关于r - R 中的双向条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64216270/