Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding legend to a single line chart using ggplot

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!!

like image 212
Kevin Liang Avatar asked Sep 05 '16 09:09

Kevin Liang


People also ask

How do I add a legend in ggplot2?

Adding a legend If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.

How do I change the legend value in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I get rid of Ggplot legend?

By specifying legend. position=”none” you're telling ggplot2 to remove all legends from the plot.


1 Answers

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.

like image 142
Axeman Avatar answered Oct 21 '22 12:10

Axeman