Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I make a legend in ggplot2 with one point entry and one line entry?
    primarykey
    data
    text
    <p>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 something like this:</p> <pre><code>names &lt;- c(1,1,1,2,2,2,3,3,3) xvals &lt;- c(1:9) yvals &lt;- c(1,2,3,10,11,12,15,16,17) pvals &lt;- c(1.1,2.1,3.1,11,12,13,14,15,16) ex_data &lt;- data.frame(names,xvals,yvals,pvals) ex_data$names &lt;- factor(ex_data$names) graph &lt;- ggplot(data=ex_data, aes(x=xvals, y=yvals, color=names)) print(graph + geom_point() + geom_line(aes(x=xvals, y=pvals))) </code></pre> <p>As you can see, both the lines and the points are colored by a categorical variable ('names' in this case). I would like the legend to contain 2 entries: a dot labeled 'Data', and a line labeled 'Fitted' (to denote that the dots are real data and the lines are fits). However, I cannot seem to get this to work. The (awesome) guide <a href="https://ggplot2.googlegroups.com/attach/916e6043b542b18d/ggplot2+4-1.pdf?gda=g9BDfUYAAAC5f3CzYMX3kmL-sjw03IF9PQERITrZJ7UznEaWnA97Soz8LCmTqTlzbSx9FGDKxIVx40jamwa1UURqDcgHarKEE-Ea7GxYMt0t6nY0uV5FIQ&amp;view=1&amp;part=2" rel="nofollow noreferrer">here</a> is great for formatting, but doesn't deal with the actual entries, while I have tried the technique <a href="https://stackoverflow.com/questions/2253179/using-ggplot2-how-can-i-represent-a-dot-and-a-line-in-the-legend">here</a> to no avail, i.e.</p> <pre><code>print(graph + scale_colour_manual("", values=c("green", "blue", "red")) + scale_shape_manual("", values=c(19,NA,NA)) + scale_linetype_manual("",values=c(0,1,1))) </code></pre> <p>The main trouble is that, in my actual data, there are >200 different categories for 'names,' while I only want the 2 entries I mentioned above in the legend. Doing this with my actual data just produces a meaningless legend that runs off the page, because the legend is trying to be a key for the colors (of which I have way too many).</p> <p>I'd appreciate any help!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload