r - 如何在堆积条形图中绘制两列
问题描述
感谢您在以下方面的帮助:我正在尝试构建一个堆叠的条形图。填充是业务(新的和更新的)拆分,Y 轴是新/更新的业务量,X 是月份。在我的数据中,我有两年的历史,所以我希望每个月有两个堆叠的列,一个用于 n-1 年,一个用于 n 年。但是,我不知道如何做这最后一步......
为了澄清,请在下面找到一张数据图片,我到目前为止的情节和我的目标图。
这是代码:
ggplot(BUSINESS, aes(fill=Business, y=GWP_mio, x=Date)) +
geom_bar(position="stack", stat="identity") +
scale_fill_manual(values = c("#009E73","Darkblue")) +
scale_y_continuous(breaks=seq(0,18000000,1000000), labels = scales::comma_format(scale = 1/1000000,
accuracy = .1), limits = c(0,18000000)) +
theme_ipsum() +
ggtitle('GWP development') +
theme(plot.title = element_text(hjust=0.5, size=14, family="Calibri", face="bold"),
legend.title = element_text(size=11, family="Calibri", face="bold"),
axis.title.x = element_text(hjust=1, size=11, family="Calibri", face="bold"),
axis.text.x = element_text(angle=90, hjust=1, size=11, family="Calibri"),
axis.title.y = element_text(angle=0, hjust=1, size=10, family="Calibri", face="bold"))
任何帮助将不胜感激。
解决方案
你要求的是两者position= 'dodge'
和position= 'stack'
。我实际上建议使用刻面:
数据
library(data.table)
library(ggplot2)
N <- 24
dat <- data.table(
date= rep(seq.Date(as.Date('2017-01-01'), as.Date('2018-12-01'), '1 month'), each= 2)
, new= rpois(n= 2 * N, lambda= 5)
, renew= rpois(n= 2 * N, lambda= 4)
)
dat[,year := data.table::year(date)]
dat[,month:= data.table::month(date)]
dat <- melt(dat, id.vars= c("date", "year", "month"), variable.name= 'business_type', value.name= 'units')
刻面
这对观众来说会容易得多。
ggplot(dat, aes(x= month, y= units, fill= factor(year))) +
geom_bar(position= 'dodge', stat='identity') + facet_grid(business_type ~ .) +
theme(axis.text.x= element_text(angle= 90))
解决方案
但这不是你要求的。所以让我们做一些hacky。你必须弄乱颜色/填充才能得到你想要的。但是在这里我们为总添加第一层,然后为新添加第二层
N <- 24
dat <- data.table(
date= rep(seq.Date(as.Date('2017-01-01'), as.Date('2018-12-01'), '1 month'), each= 2)
, new= rpois(n= 2 * N, lambda= 5)
, renew= rpois(n= 2 * N, lambda= 4)
)
dat[,year := data.table::year(date)]
dat[,month:= data.table::month(date)]
dat[, total := new + renew]
ggplot(dat, aes(x= month, y= total, fill= factor(year))) +
geom_bar(stat= 'identity', position= 'dodge', ) +
geom_bar(data= dat, aes(x= month, y= new, fill= "black", colour= factor(year)), stat= 'identity', position= 'dodge') +
scale_color_brewer(palette = "Dark2")
推荐阅读
- javascript - 使用画布显示的类似图像
- python - 找到每月不相等值的平均值并根据某些条件进行分配
- javascript - 如何创建音乐机器人
- sql - 在左连接中从外部表中选择单行
- javascript - 如何在粘性导航栏功能(onscroll)和 onclick 功能中嵌套 JS 媒体查询?
- c++ - boost::make_optional 类型说明
- azure - Azure rest api 相当于 az sql db show-connection-string -s myserver -n mydb -c ado.net
- javascript - 使用 Array.fill() 在没有引用的情况下在一行中声明 ES6 多个变量会导致问题
- mysql - 我无法使用 MySQL shell 连接 root@localhost
- r - 检查预测库中 NNETAR 函数的残差