gpt4 book ai didi

r - 用 par(new=TRUE) 像两个条形图一样覆盖两个 geom_bar

转载 作者:行者123 更新时间:2023-12-04 06:18:48 26 4
gpt4 key购买 nike

我目前有一个与此类似的情节:

sourceTable<-"dateValues;total;inHospital
2014-01-01; 80; 20
2014-01-02; 90; 15
2014-01-03; 98; 16
2014-01-04; 98; 17
2014-01-05; 100; 28
2014-01-06; 110; 28
2014-01-07; 122; 30
2014-01-08; 110; 25
2014-01-09; 100; 22
2014-01-00; 90; 20
2014-01-11; 90; 15
2014-01-12; 80; 13
2014-01-13; 82; 10"

timetable<-read.table(textConnection(sourceTable), sep=";", head=T, dec=",")
barplot(timetable$total, border="red", axes=FALSE, ylim=c(0, max(timetable$total)))
par(new=TRUE)
barplot(timetable$inHospital, border="blue", axes=FALSE, ylim=c(0, max(timetable$total)))

这给了我这个情节:

two overlayed barplots

有没有办法像这样使用 ggplot 和 geom_bar 做到这一点:
library(ggplot2)
ggplot(timetable, aes(x=dateValues, y=total))
+geom_bar(stat="identity", fill="red", colour="red")

如何在第一个上覆盖第二个 ggplot,即:
ggplot(timetable, aes(x=dateValues, y=inHospital))
+geom_bar(stat="identity", fill="red", colour="blue")

最佳答案

尝试这个:

library(ggplot2)

ggplot(data = timetable, aes(x = dateValues, y = total)) +
geom_bar(stat = "identity", fill = "grey", colour = "red")+
geom_bar(data = timetable, aes(x = dateValues, y = inHospital),
stat = "identity", fill = "grey", colour = "blue")

enter image description here

编辑:
替代方法 - 正确的方法 - 在绘图之前转换数据:
library(reshape2)
library(ggplot2)

# transform the data - melt
timetable$outHospital <- timetable$total - timetable$inHospital
df <- melt(timetable, id = c("dateValues", "total"))

# plot in one go
ggplot(data = df, aes(x = dateValues, y = value, fill = variable)) +
geom_bar(stat = "identity")

enter image description here

关于r - 用 par(new=TRUE) 像两个条形图一样覆盖两个 geom_bar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25661829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com