2015-10-30 81 views
1

我有一个数据集,我需要在三个时间段内为两个队列表示一个堆积条形图。目前,我每年都要面对面,并根据我的DV的概率值进行填充(有人前往养老院的时间t,即t = 0,t = 1,... t> = 5) 。我试图弄清楚是否可以引入另一个色标,以便每个“比较”栏都用黄色渐变填充,处理栏将填充蓝色渐变。我想这样做的最好方法可能是覆盖这两个地块,但我不确定是否可以在ggplot(或其他包)中执行此操作。代码和屏幕截图如下:ggplot2中具有两个色阶的并排堆叠条形图

  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") 

enter image description here

+0

请提供一些样品数据使这个例子具有可重现性。 – JasonAizkalns

+0

'gridExtra :: grid.arrange()'可能会派上用场。 –

回答

3

你可能要考虑使用interaction() - 这里有一个可重复的解决方案:

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)) 

Plot

+0

这是完美的;谢谢! – ymediceacuerdate

相关问题