使用ggplot将图例添加到单个折线图 [英] 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.
c> ggplot(mtcars,aes(x = mpg,y = wt))+ geom_line(stat =identity)+ scale_fill_identity(name =,guide =legend,labels = c(myLegend))
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:
图中没有显示图例,我想要的是以下内容:
The legend is not shown in the plot and what I want is the following:
我使用Matlab绘图。有谁能告诉我如何在R中做到这一点?非常感谢你!
which I plot using Matlab. Could anyone tell me how to do it in R? Thank you so much!!
推荐答案
你的绘图并没有显示图例,因为没有美学映射到这一行。基本上,ggplot没有理由添加图例,因为只有一行。
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()
您可以看看?scale_linetype
,以获取有关如何修改tthat图例的信息。
You can have a look at ?scale_linetype
for information on how to modify tthat legend.
例如,使用 + scale_linetype('MyLegendTitle')
更改图例标题。
For example, use + scale_linetype('MyLegendTitle')
to change the legend title.
这篇关于使用ggplot将图例添加到单个折线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!