2013-02-21 99 views
8

我試圖覆蓋兩個不同的地塊。一個是geom_boxplot,另一個是geom_jitter。我希望每個人都有自己的色彩比例。但是當我添加第二個色標時,我給出了錯誤ggplot2 - 對覆蓋地塊使用兩種不同的色階

"Scale for 'fill' is already present. Adding another scale for 'fill', 
    which will replace the existing scale." 

我假設我做錯了什麼。任何意見將是感激

這是我工作的代碼粗略的例子:

P <- ggplot(dat) + 
      geom_boxplot(aes(x=ve, y=metValue, fill=metric), alpha=.35, w=0.6, notch=FALSE, na.rm = TRUE) + 
      scale_fill_manual(values=cpalette1) + 
      geom_hline(yintercept=0, colour="#DD4466", linetype = "longdash") + 
      theme(legend.position="none") 

P + geom_jitter(dat2, aes(x=ve, y=metValue, fill=atd), 
       size=2, shape=4, alpha = 0.4, 
       position = position_jitter(width = .03, height=0.03), na.rm = TRUE) + 
       scale_fill_manual(values=cpalette2) 

datdat2具有相同的架構,但不同的值。

我發現了幾個解決覆蓋圖的例子,但沒有一個解決這個問題。

回答

11

首先,製作兩個與示例中名稱相同的示例數據幀。

dat<-data.frame(ve=rep(c("FF","GG"),times=50), 
       metValue=rnorm(100),metric=rep(c("A","B","D","C"),each=25), 
       atd=rep(c("HH","GG"),times=50)) 
dat2<-data.frame(ve=rep(c("FF","GG"),times=50), 
       metValue=rnorm(100),metric=rep(c("A","B","D","C"),each=25), 
       atd=rep(c("HH","GG"),times=50)) 

我認爲你不需要使用參數fill=geom_jitter()因爲shape=4顏色也與colour=參數進行設置。然後您可以使用scale_colour_manual()來設置您的值。而不是cpallete只是使用顏色的名稱。

P <- ggplot(dat) + 
    geom_boxplot(aes(x=ve, y=metValue, fill=metric), alpha=.35, w=0.6, notch=FALSE, na.rm = TRUE) + 
    geom_hline(yintercept=0, colour="#DD4466", linetype = "longdash") + 
    scale_fill_manual(values=c("red","blue","green","yellow"))+ 
    theme(legend.position="none") 

P + geom_jitter(data=dat2, aes(x=ve, y=metValue, colour=atd), 
       size=2, shape=4, alpha = 0.4, 
       position = position_jitter(width = .03, height=0.03), na.rm = TRUE) + 
       scale_colour_manual(values=c("red","blue")) 

enter image description here