在R中使用ggplot2修改图例

3

我目前正在使用ggplot包来绘制一个带有N(0,1)密度曲线的正态变量直方图。我对这个包非常陌生,我正在使用的代码是:

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

这段代码生成了下面的图表。我如何更改图例,以便用填充的蓝色框(代表直方图的条形)替换表示直方图的线条?谢谢!

还要看看 geom_density()。在我看来比 stat_function(...) 更容易。 - Chase
1个回答

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替换。例如,上面的最后两行将变为:

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

谢谢您的评论,但是现在图例似乎被分成了两个图例,直方图的柱形之间也没有线条进行分隔。 - A-A
1
aes之外添加colour='black'geom_histogram将会在条形图上带回线条,但是会在图例中添加一条对角线。在ggplot2中有两个图例,因为这是你描述的方式,就是这样。如果你想要对图例进行极其精细的控制,请使用基本绘图函数。ggplot2在这里抵制你,因为你试图创建一个可以说是“不好”的图例,或者至少是根据ggplot2背后的哲学来看是不必要的。 - joran
1
xyplot函数的key=list()参数还可以调整图例中线条的宽度。 - IRTFM
有一个拼写错误:theme(legend.background = elemenet_blank()),应该是 element_blank - qed
我尝试了,但系统不允许这样的小修改,它说至少需要6个字符。 :) - qed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接