2
votes

So, I have a problem with ggplot2 that seems too trivial, but out of five different approaches, none produced the desired result. I wish to change the legend title of a plot of a continuous variable over the years by the category of a second variable. In that way, if I have three categories in the second variable, I'll have three lines of the continuous variable over the years. I use the mtcars data to try to replicate my intent and problem. So, my code is similar to the following:

mt <- ggplot(data=mtcars,aes(x=factor(cyl),linetype=factor(am),y=mpg))
mt <- mt+geom_line(aes(group=factor(am)),size=0.8)
mt <- mt+labs(y='Number of cylinders',x='Mileage per galon',color='Transmission')

In this case, my continuous variable is mpg, while my Years variable would be cyl, number of cylinders, and factor variable is am. I tried to change the legend title by using color, inside labs, but that was unfruitful. I tried other options too, which are scale_color_discrete() function, fill, guides() function, scale_fill_discrete() function, also to no avail. So, my intent is to change my legends title. Following, the graph originated by the code above.

How would anyone go about changing that factor(am) title legend?

1
Could you include a sample of your expected plot?NelsonGon
I'd like to change just the legend title factor(am) to something like Transmission.b12536
Just use fill argument in labs. fill="Transmission"(I hadn't checked it's linetype not fill)NelsonGon

1 Answers

2
votes
mt <- ggplot(data=mtcars,aes(x=factor(cyl),linetype=factor(am),y=mpg))
mt <- mt+geom_line(aes(group=factor(am)),size=0.8)
mt <- mt+labs(y='Number of cylinders',x='Mileage per galon', linetype='Transmission')

Produces this plot:

enter image description here

Explanation: You used the elements x, y and linetype but then tried to assign a string to the legend for color which you didn't use. That's why it had no effect. Changing the parameter to linetype solves this.