b12536
b12536

Reputation: 23

How to change the legend title of a ggplot categorized by the factor of a variable

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?

Upvotes: 2

Views: 869

Answers (1)

dario
dario

Reputation: 6483

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.

Upvotes: 2

Related Questions