【发布时间】:2017-11-08 04:51:04
【问题描述】:
我正在尝试按照以下思路在 ggplot 中创建图表:
...其中框的颜色由一个变量表示,框的轮廓由另一个变量表示。
假设数据结构如下:
df<-data.frame(index=1:50,date=sample(seq(as.Date('1999/01/01'), as.Date('1999/06/01'), by="day"), 50,replace=T),
V1=sample(c("Indigenous","Import-related","Imported","Unknown"), 50,replace=T),
V2=sample(c(NA,"Zombie","Pulmonary Hemorrhage"), 50,replace=T))
我能想到的都是这样的:
require(ggplot2)
#draw the histogram with fill determined by V1
p<-ggplot(data=df)+geom_histogram(aes(x=date,group=V1,fill=V1),binwidth=7,color="black",alpha=0.9)
#draw the individual boxes for each case
p1<-p+scale_fill_discrete()+geom_histogram(aes(x=date,group=index),binwidth=7,color="black",alpha=0)
#attempt to draw green boxes for one value of V2
p2<-p1+geom_histogram(aes(x=date,group=V2=="Zombie"),binwidth=7,color="green",alpha=0,size=1.2)
#attempt to draw orange boxes for the other value of V2
p3<-p2+geom_histogram(aes(x=date,group=V2=="Pulmonary Hemorrhage"),binwidth=7,color="orange",alpha=0,size=1.2)
但是,这不起作用,因为它在任何地方都绘制了边界,并且我无法使用这种方法隔离个别案例,如您所见。
有 ggplot 解决方案吗?如果我不能做彩色框,我可以在适当的框上通过某种文本注释来指示 V2,但随后必须为每个标签找出 x 和 y,这也让我很合适。
【问题讨论】:
-
日期 V1、V2 组合每个组合提供 1 条记录,请检查您的数据集吗?
-
@Hardikgupta,谢谢 - 虽然不知道你的意思。日期、V1 和 V2 组合相同的案例不超过一个是否有问题?在这个例子中,这对我来说似乎是合理的。但是,如果它有助于您思考这个问题,我将添加一个数据集,其中保证每个组合至少有 2 条记录。 (单独评论)
-
@Hardikgupta:尝试使用此代码,每个变量组合将为您提供至少 2 个案例。尽管如果您能告诉我为什么这很重要,我将不胜感激!
df2<-data.frame(index=1:25,date=seq(as.Date('1999/01/01'), as.Date('1999/01/01')+24, by="day"), V1=sample(c("Indigenous","Import-related","Imported","Unknown"), 50,replace=T), V2=sample(c(NA,"Zombie","Pulmonary Hemorrhage"), 50,replace=T)) df<-rbind(df2,df2)