2015-09-28 123 views
0

我對ggplot2比較新,想知道是否有一種簡單的方法來更改圖例。我在以前的回答Control column widths in a ggplot2 graph with a series and inconsistent data之後爲我的數據框添加了一個虛擬變量(AEmpty,在下面的示例中),該變量說明了不均勻因數的間距和條寬。這看起來似乎是最簡單的方法 - 儘管可能對其他方式進行評論或回答是值得歡迎的!更改ggplot2中的圖例屬性

所以在下面的例子中,我得到一個看起來像這樣的繪圖輸出。 enter image description here

我的問題是(1)有沒有辦法從'後'選擇灰度,從而最大化顯示條之間的顏色對比度? (2)在圖例中,我如何刪除AEmpty?我在這裏看到類似的問題How do I manually change the key labels in a legend in ggplot2但這裏的答案不起作用,因爲我已經在其他地方應用了填充函數,而scale_fill_discrete不起作用。

此外,如果有人會知道更容易的方法來縮放x軸因子,從而消除這個「虛擬」變量的需要,一個答案將不勝感激。最終,所需的輸出是一個barplot,每個bar具有相同的寬度,並且x軸上的每個「站點」等距離分佈,只有相關因素顯示在鍵中。

library(ggplot2) 
#Create data 
when <- as.factor(c(rep(c("Before","After"),each = 3), 
     rep("During", 2),"AEmpty")) 
site <- as.factor(c(rep(c("a","b","c"), 2), 
     "b","a","c")) 
mean <- c(6,4.5,4.5,1.75,3.25,2.5,3,0,0) 
std_error <- c(2.31,1.04,0.5,0.63,1.70,1.32,1.53,NA,NA) 
df <- data.frame(when,site,mean,std_error) 
#Plot 
limits <- aes(ymax = mean + std_error, ymin=mean-std_error) 
g <- ggplot(df, aes(site,mean,fill=when)) + geom_bar(stat = "identity", position = position_dodge()) + geom_errorbar(limits, width = 0.25, position = position_dodge(width = 0.9)) + scale_fill_grey() 
g 
+0

提供簡單重複的例子,或你的數據集的一部分 – Koundy

+0

更改爲創建自己的假人的:'summarised_df < - rbind(summarised_df,C( 「在」, 「一個」,NA,NA), C( 「在」 ,「c」,NA,NA))' – Roland

+0

示例數據已被編輯,現在有希望更清楚了,謝謝。 –

回答

1

我不完全確定你的意思是:「我已經在別處應用了填充函數」。由於fill只能在每個圖形中出現一次,所以可以將breakslabels併入您的「其他填充函數」中,而您在此處不顯示該函數。

下面的代碼,你想要做什麼,你所提供的例子:

library(ggplot2) 
# Create data 
when <- as.factor(c(rep(c("Before","After"),each = 3), 
        rep("During", 2),"AEmpty")) 
site <- as.factor(c(rep(c("a","b","c"), 2), 
        "b","a","c")) 
mean <- c(6,4.5,4.5,1.75,3.25,2.5,3,0,0) 
std_error <- c(2.31,1.04,0.5,0.63,1.70,1.32,1.53,NA,NA) 
df <- data.frame(when,site,mean,std_error) 

# Plot 
limits <- aes(ymax = mean + std_error, ymin=mean-std_error) 

ggplot(df, aes(site,mean,fill=when)) + 
    geom_bar(stat = "identity", position = position_dodge()) + 
    geom_errorbar(limits, width = 0.25, position = position_dodge(width = 0.9)) + 
    scale_fill_manual(values = c("AEmpty" = "grey1", 
           "After" = "grey15", 
           "Before" = "grey55", 
           "During" = "grey75"), 
        breaks = c("After", "Before", "During"), 
        labels = c("After", "Before", "During")) 

要選擇的灰色陰影,諮詢this list of R-colours

+1

非常感謝你! –