How can I make a legend in ggplot2 with one point entry and one line entry?

前端 未结 2 984
[愿得一人]
[愿得一人] 2020-12-19 15:07

I am making a graph in ggplot2 consisting of a set of datapoints plotted as points, with the lines predicted by a fitted model overlaid. The general idea of the graph looks

相关标签:
2条回答
  • 2020-12-19 15:22

    This has been answered already, but based on feedback I got to another question (How can I fix this strange behavior of legend in ggplot2?) this tweak may be helpful to others and may save you headaches (sorry couldn't put as a comment to the previous answer):

    ggplot(ex_data, aes(x=xvals, group=names)) + 
      geom_point(aes(y=yvals, shape='data', linetype='data')) + 
      geom_line(aes(y=pvals, shape='fitted', linetype='fitted')) + 
      scale_shape_manual('', values=c('data'=19, 'fitted'=NA)) + 
      scale_linetype_manual('', values=c('data'=0, 'fitted'=1))
    
    0 讨论(0)
  • 2020-12-19 15:42

    I think this is close to what you want:

    ggplot(ex_data, aes(x=xvals, group=names)) + 
      geom_point(aes(y=yvals, shape='data', linetype='data')) + 
      geom_line(aes(y=pvals, shape='fitted', linetype='fitted')) + 
      scale_shape_manual('', values=c(19, NA)) + 
      scale_linetype_manual('', values=c(0, 1))
    

    The idea is that you specify two aesthetics (linetype and shape) for both lines and points, even though it makes no sense, say, for a point to have a linetype aesthetic. Then you manually map these "nonsense" aesthetics to "null" values (NA and 0 in this case), using a manual scale.

    0 讨论(0)
提交回复
热议问题