r - R 中的双向条形图

标签 r ggplot2 bar-chart

感谢您提前提供的帮助。我对 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/

相关文章:

R:颜色键的 sf 绘图大小

删除嵌套在数据框列表中的列标题内的句点和空格

r - 确定 R data.frame 列中值的变化位置

r - R错误: I get this error message (in R) when trying to use a for loop with a if statement, missing value where TRUE/FALSE needed [duplicate]

R:geom_point() 使用函数来选择形状?

r - 在ggplot2中绘制运行平均值

R ggplot geom_bar 错误 : Discrete value supplied to continuous scale

javascript - dc.js 条形图中的目标

postgresql - matplotlib 条形图 : How to spread bars evenly in a postgres-generate_series?

Python 排序图