Adding a legend to a single line chart using ggplot

I'm just trying to make a line chart and add a legend to it using ggplot in R. Below 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 displayed on the chart, and I want the following: enter image description here

which I use with matlab. Can someone tell me how to do this in R? Thank you very much!

+4
source share
1 answer

The legend is not displayed in the plot, because there is no aesthetics matched with the line. In principle, ggplot sees no reason to add a legend, since there is only one line.

:

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

enter image description here

?scale_linetype , .

, + scale_linetype('MyLegendTitle') .

+3

Source: https://habr.com/ru/post/1653661/


All Articles