我是R的新用户,正在尝试向图线中添加图例。这是我用来绘制图和相对图的命令行。
ggplot(crab_tag$daylog, aes(Date))+ geom_line(aes(y=-Max.Depth), color="blue")+ geom_line(aes(y=-Min.Depth),color="violet")+ labs(x="Date",y="Depth(m)")+ theme(legend.position = c(0,1),legend.justification = c(0,1)) +scale_color_manual(values = c("blue","violet"))
任何人都可以帮助我查看我的错误吗? 谢谢!
答案 0 :(得分:0)
基于该线程https://community.rstudio.com/t/adding-manual-legend-to-ggplot2/41651/2,我发现了以下问题:这里的问题是您必须将颜色链接到图例(也必须调用图例)。这是一个解决方案:
library(tidyverse)`
library(learningr)`
ggplot(crab_tag$daylog, aes(Date)) +
geom_line(aes(y=-Max.Depth, colour = "Max.Depth")) +
geom_line(aes(y=-Min.Depth, colour = "Min.Depth"))+
labs(x="Date",y="Depth(m)", colour = "legend")+
theme(legend.position = c(0,1),legend.justification = c(0,1)) +
scale_color_manual(values = c("Max.Depth"="blue","Min.Depth"="violet"))
您会看到,主要的更改是在aes()
函数中调用了color,并在其中定义了要在图例中使用的变量名称,实验室中颜色图例的标签以及值的命名矢量在scale_colour_manual()