ggplot2: Change legend symbol

人走茶凉 提交于 2019-12-01 16:35:17

问题


I have plotted several lines and I am wondering how to change the symbol in the legend to go from the thin line to a full block.

I am trying to go from

to

(while using geom_line and not geom_bar)


回答1:


You can use function guides() and then with argument override.aes= set line size= (width) to some large value. To remove the grey area around the legend keys set fill=NA for legend.key= inside theme().

df<-data.frame(x=rep(1:5,each=3),y=1:15,group=rep(c("A","B","C"),each=5))
ggplot(df,aes(x,y,color=group,fill=group))+geom_line()+
  guides(colour = guide_legend(override.aes = list(size = 10)))+
  theme(legend.key=element_rect(fill=NA))




回答2:


Starting in ggplot2_3.2.0, you can choose which glyph you want displayed in the legend keys using the key_glyph argument in the geom_*().

For example, you want to use rectangles instead of lines as your glyph. In that case you can do

df = data.frame(x = rep(1:5, each=3),
                y = 1:15,
                group = rep(c("A", "B", "C"), each=5))

ggplot(df, aes(x, y, color=group) )+
    geom_line(key_glyph = "rect")

See ?draw_key for a list of the current glyphs available.



来源:https://stackoverflow.com/questions/19456816/ggplot2-change-legend-symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!