[英]How to create geom_bar next to each other from different databases
I'm struggling with trying to create a simple bar graph where the bars are next to each other(like pictured).我正在努力创建一个简单的条形图,其中条形图彼此相邻(如图所示)。
The data are from different databases.数据来自不同的数据库。
Database A
Month Cost
1 Dec 3009
2 Dec 3468
3 Nov 3420
4 Oct 3162
Database B
Month Cost
1 Dec 309
2 Nov 3481
3 Nov 3419
4 Oct 3120
For the bar graph, I am trying to show a bar graph that has the X-axis as the month, and for month Dec, A would have 2 (the total count, not the value), B = 1, for month Nov, A would have 1, and B would have 2. Thank you!对于条形图,我试图显示一个以 X 轴为月份的条形图,对于 12 月,A 将有 2(总数,而不是值),B = 1,对于 11 月, A 有 1,B 有 2。谢谢!
You could add an id variable to your datasets, bind them by row and make a standard bar chart where you map id on fill
:您可以将 id 变量添加到数据集,按行绑定它们并制作标准条形图,其中 map id
fill
:
db1 <- read.table(text = "Month Cost
1 Dec 3009
2 Dec 3468
3 Nov 3420
4 Oct 3162", header = TRUE)
db2 <- read.table(text = "Month Cost
1 Dec 309
2 Nov 3481
3 Nov 3419
4 Oct 3120", header = TRUE)
library(ggplot2)
library(dplyr)
db <- dplyr::bind_rows(list(A = db1, B = db2), .id = "id")
db$Month <- factor(db$Month, levels = month.abb)
ggplot(data = db, mapping = aes(Month, fill = id)) +
geom_bar(position = "dodge")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.