9

I just try to make a line chart and add a legend to it using ggplot in R. The following is my code.

ggplot(mtcars, aes(x=mpg, y=wt)) + geom_line(stat = "identity") + scale_fill_identity(name = "", guide = "legend", labels = c("myLegend"))

and I got the following: enter image description here

The legend is not shown in the plot and what I want is the following: enter image description here

which I plot using Matlab. Could anyone tell me how to do it in R? Thank you so much!!

1 Answer 1

8

You plot is not showing a legend, because there are no aesthetics mapped to the line. Basically, ggplot sees no reason to add a legend as there's only one line.

A simple way to get a legend is to map the line type to a character string:

ggplot(mtcars, aes(x=mpg, y=wt, lty = 'MyLegend')) + geom_line()

enter image description here

You can have a look at ?scale_linetype for information on how to modify tthat legend.

For example, use + scale_linetype('MyLegendTitle') to change the legend title.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.