如何使用点图将图例添加到ggplot2线? [英] How to add legend to ggplot2 line with point plot?

查看:299
本文介绍了如何使用点图将图例添加到ggplot2线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了许多代码,但始终无法为图形添加图例.我想为测量的红点和模拟黑线添加图例

I have tried many codes, but always fail to add legend for the graph.I want to add legend for measured red point and simulated black lineThe graph is still missing legend with the code below

    library(foreign)
    library(ggplot2)
    library(dplyr)
    library(readxl)
    library(scales)
    Sys.setlocale("LC_TIME", "English")
    X0_40cm <- read_excel("C:/Users/Connie/Desktop/LAI/Wheat_2017-2018.xlsx")
    View(X0_40cm)
    ggplot(X0_40cm, aes(Date,LAI,group=1))+
      geom_point(data=subset(X0_40cm, Condition=="Measured"),col="red")+
      geom_line(data=subset(X0_40cm, Condition=="Simulated"),col="black")+
      theme(legend.position=c(0.85,0.80))+
      scale_y_continuous(limits = c(0,3)) +
      labs(title="Winter wheat of I plot",y="LAI",x="Date")+
      theme_update(plot.title=element_text(hjust=0.5))

推荐答案

仅当您在颜色美学上映射变量时,才会绘制自动图例.在您的情况下,将条件"设置为颜色"并手动设置颜色.试试这个:

An automatic legend is only drawn if you map a variable on the color aesthetic. In your case map Condition on color and set colors manually. Try this:

    ggplot(mapping = aes(Date, LAI, color = Condition, linetype = Condition, shape = Condition))+
  geom_point(data=subset(X0_40cm, Condition=="Measured"))+
  geom_line(data=subset(X0_40cm, Condition=="Simulated"))+
  scale_color_manual(values = c("red", "black")) +
  scale_linetype_manual(values=c(NA,1)) +
  scale_shape_manual(values=c(16,NA)) +
  theme(legend.position=c(0.85,0.80))+
  scale_y_continuous(limits = c(0,3)) +
  labs(title="Winter wheat of I plot",y="LAI",x="Date")
  theme_update(plot.title=element_text(hjust=0.5))

这篇关于如何使用点图将图例添加到ggplot2线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆