将图例中的 ggplot 彩色线条更改为正方形或圆形

Posted

技术标签:

【中文标题】将图例中的 ggplot 彩色线条更改为正方形或圆形【英文标题】:Change ggplot coloured lines in legend to squares or circles 【发布时间】:2012-09-01 03:15:42 【问题描述】:

除了当前构成图例键的灰色背景上的彩色线条,我希望键标签旁边有颜色的正方形或圆形,以便使颜色易于看到。我怎样才能做到这一点?下面是一个代码 sn-p 用作示例:

 mry <- do.call(rbind, by(movies, round(movies$rating), function(df) 
   nums <- tapply(df$length, df$year, length)
   data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)),
   number=as.vector(nums))
 ))

ggplot(mry, aes(x=year, y=number, colour=factor(rating))) + geom_line() +
scale_colour_brewer(palette="YlGnBu")

【问题讨论】:

【参考方案1】:

一个黑客来做圈......

ggplot(mry, aes(x=year, y=number, colour=factor(rating))) +
  scale_colour_brewer(palette="YlGnBu") +  
  geom_point()  +      
  geom_point(size=5,colour="white",show_guide=FALSE)  +
  opts(
    panel.background = theme_rect(fill =  "transparent"), 
    panel.grid.minor = theme_blank(),
    panel.grid.major = theme_blank(),
    plot.background = theme_rect(fill = "transparent",colour = NA)
  ) +  geom_line(show_guide=FALSE)

【讨论】:

你可以通过改变点的形状来制作正方形等 如果您想要更大的圆形和正方形的大小,也可以轻松编辑 更新 opts 现已弃用,使用theme 并将theme_rect 替换为element_rect 等...

以上是关于将图例中的 ggplot 彩色线条更改为正方形或圆形的主要内容,如果未能解决你的问题,请参考以下文章