2011-07-16 134 views
3

我正在使用ggplot軟件包繪製N(0,1)密度疊加的正常變量直方圖。我對這個軟件包很陌生,我使用的代碼是在R中使用ggplot2修改圖例

x = rnorm(1000) 
qplot(x, geom = 'blank') +  
    geom_histogram(aes(y = ..density.., colour = 'Histogram'), legend = FALSE, 
    binwidth = 0.5, fill = "blue") +       
    stat_function(fun = dnorm, aes(colour = 'Density'))+ 
    scale_x_continuous('x', limits = c(-4, 4))+ 
    opts(title = "Histogram with Overlay")+ 
    scale_colour_manual(name = 'Legend', values = c('darkblue', 'red')) + 
    scale_y_continuous('Frequency')+ 
    opts(legend.key=theme_rect(fill="white",colour="white"))+ 
    opts(legend.background = theme_rect()) 

此代碼產生下圖。如何更改圖例,以便將代表直方圖的線替換爲填充的藍色框(代表直方圖的條)?謝謝!

Histogram With Overlay

+0

也檢出'geom_density()'。比'stat_function(...)更容易'恕我直言。 – Chase

回答

4

也許這樣的事情...

dat = data.frame(x=rnorm(1000)) 
ggplot(dat,aes(x=x)) + 
    geom_histogram(aes(y=..density..,fill="Histogram"),binwidth=0.5) + 
    stat_function(fun = dnorm, aes(colour= "Density")) + 
    scale_x_continuous('x', limits = c(-4, 4)) + 
    opts(title = "Histogram with Overlay") + 
    scale_fill_manual(name="",value="blue") + 
    scale_colour_manual(name="",value="red") + 
    scale_y_continuous('Frequency')+ 
    opts(legend.key=theme_rect(fill="white",colour="white"))+ 
    opts(legend.background = theme_blank()) 

注意:自版本0.9.2 opts已經theme一直replaced。例如,上面的最後兩行應該是:

theme(legend.key = element_rect(fill = "white",colour = "white")) + 
theme(legend.background = element_blank()) 
+0

感謝您的評論,但現在傳奇似乎分裂成兩個傳說,也沒有線條分隔直方圖的酒吧。 –

+1

將'color ='black''添加到'aes'之外的'geom_histogram'將會帶回條上的線條,但會在圖例中添加一條對角線。有兩個傳說,因爲這就是你在ggplot2中描述的方式,即故事結束。如果你想非常精確地控制傳說,堅持基地繪圖功能。 ggplot2在這裏抵制你,因爲你試圖創造一個可以說是「壞」的傳說,或者至少根據ggplot2背後的哲學創造一個不必要的傳說。 – joran

+0

謝謝你的幫助。 –