开发者

Modify Legend using ggplot2 in R

I'm currently using the ggplot package to plot a histogram of normal variates with a N(0, 1) density overlay. I'm very new to this package and the code I'm using is

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")+
  sc开发者_如何学Cale_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())

This code produces the following diagram. How do I change the legend so that the line representing the histogram is replaced with a filled blue box (that represents the bars of the histogram)? Thank You!

Modify Legend using ggplot2 in R


Maybe something like this...

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

Note: Since version 0.9.2 opts has been replaced by theme. So for example, the last two lines above would be:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜