簡體   English   中英

在 R 中使用 ggplot2 修改圖例

[英]Modify Legend using ggplot2 in R

我目前正在使用 ggplot package 到 plot 具有 N(0, 1) 密度疊加的正態變量直方圖。 我對這個 package 很陌生,我使用的代碼是

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

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

帶疊加的直方圖

也許像這樣的東西......

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM