2011-07-16 133 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

谢谢你的帮助。 –