R ggplot2中带有两个色标的并排堆叠条形图

R ggplot2中带有两个色标的并排堆叠条形图,r,ggplot2,data-visualization,facet,stackedbarseries,R,Ggplot2,Data Visualization,Facet,Stackedbarseries,我有一个数据集,其中我需要表示三个时间段内两个队列的堆叠条形图。目前,我正在按年份分面,并根据我的DV的概率值填充有人去养老院的次数t;t=0,t=1。。。t>=5。我试图弄清楚是否有可能引入另一种色阶,这样每个对比条都将填充黄色渐变,而treatmetn条将填充蓝色渐变。我认为最好的方法可能是覆盖两个图,但我不确定是否可以在ggplot或其他包中这样做。代码和屏幕截图如下: tempPlot <- ggplot(tempDF,aes(x = HBPCI, y = mar

我有一个数据集,其中我需要表示三个时间段内两个队列的堆叠条形图。目前,我正在按年份分面,并根据我的DV的概率值填充有人去养老院的次数t;t=0,t=1。。。t>=5。我试图弄清楚是否有可能引入另一种色阶,这样每个对比条都将填充黄色渐变,而treatmetn条将填充蓝色渐变。我认为最好的方法可能是覆盖两个图,但我不确定是否可以在ggplot或其他包中这样做。代码和屏幕截图如下:

         tempPlot <- ggplot(tempDF,aes(x = HBPCI, y = margin,  fill=factor(prob))) + 
      scale_x_continuous(breaks=c(0,1), labels=c("Comparison", "Treatment"))+
      scale_y_continuous(labels = percent_format())+
      ylab("Prob snf= x")+
      xlab("Program Year")+
      ggtitle(tempFlag)+
      geom_bar(stat="identity")+
      scale_fill_brewer(palette = "Blues")+ #can change the color scheme here.
      theme(axis.title.y =element_text(vjust=1.5, size=11))+
      theme(axis.title.x =element_text(vjust=0.1, size=11))+
      theme(axis.text.x = element_text(size=10,angle=-45,hjust=.5,vjust=.5))+
      theme(axis.text.y = element_text(size=10,angle=0,hjust=1,vjust=0))+
      facet_grid(~yearQual, scales="fixed")

<>你可能想考虑使用交互——这是一个可重复的解决方案:

year <- c("BP", "PY1", "PY2")
type <- c("comparison", "treatment")

df <- data.frame(year = sample(year, 100, T),
                 type = sample(type, 100, T),
                 marg = abs(rnorm(100)),
                 fact = sample(1:5, 100, T))
head(df)
#   year       type      marg fact
# 1   BP comparison 0.2794279    3
# 2  PY2 comparison 1.6776371    1
# 3   BP comparison 0.8301721    2
# 4  PY1  treatment 0.6900511    1
# 5  PY2 comparison 0.6857421    3
# 6  PY1  treatment 1.4835672    3

library(ggplot2)

blues <- RColorBrewer::brewer.pal(5, "Blues")
oranges <- RColorBrewer::brewer.pal(5, "Oranges")

ggplot(df, aes(x = type, y = marg, fill = interaction(factor(fact), type))) +
  geom_bar(stat = "identity") +
  facet_wrap(~ year) +
  scale_fill_manual(values = c(blues, oranges))

请提供一些示例数据以使此示例具有可复制性。gridExtra::grid.arrange可能会派上用场。