【问题标题】:Create a ggplot barchart/histogram with fill and outline colors indicated by different variables创建一个 ggplot 条形图/直方图,其中填充和轮廓颜色由不同的变量指示
【发布时间】: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&lt;-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&lt;-rbind(df2,df2)

标签: r ggplot2 histogram


【解决方案1】:

我们可以这样尝试

df<-data.table(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))

df <- df[,.(count=.N), by = .(date,V1,V2)]

windows()
ggplot(data = df, aes(x = date, y = count, color = V2, fill = V1)) +
  geom_bar(stat = "identity", position = "stack", width = 2, size = 1) + 
  scale_fill_manual(values=c("red4", "blue4", "green4", "blue")) + 
  scale_color_manual(values=c("orange", "green", "black")) +
  scale_y_continuous(breaks = seq(1,3,1))

【讨论】:

  • 感谢 Hardik - 虽然我正在寻找 7 天间隔内的分箱直方图。这里的另一个视觉问题是相邻的条相互重叠,因此难以阅读。
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 2013-04-23
  • 2021-10-29
  • 2015-04-04
相关资源
最近更新 更多