How to add manual colors for a ggplot2 (geom_smooth/geom_line)

后端 未结 1 518
难免孤独
难免孤独 2021-02-09 03:38

I want to built a plot with ggplot2. Therefore i use geom_line to visualize lines and geom_smooth to show the Min-Max-Range of a specific index. Two data frames were used, the

相关标签:
1条回答
  • 2021-02-09 03:40

    First, it's always nice to include sample data with any plotting code otherwise we can't run it to see what you see. Please read how to make a great R reproducible example before making other posts. It will make it much easier for people to help you. Anyway, here's some sample data

    Sample_EVI2_A_SPOT<-data.frame(
        Date=seq(as.Date("2014-01-01"), as.Date("2014-02-01"), by="1 day"),
        Tomato = cumsum(rnorm(32))
    )
    Grouped_Croptypes_EVI2<-data.frame(
        Date=seq(as.Date("2014-01-01"), as.Date("2014-02-01"), by="1 day"),
        Vegetable_mean=cumsum(rnorm(32))
    )
    Grouped_Croptypes_EVI2<-transform(Grouped_Croptypes_EVI2,
        Vegetable_max=Vegetable_mean+runif(32)*5,
        Vegetable_min=Vegetable_mean-runif(32)*5
    )
    

    And this should make the plot you want

    EVI2_veg <- ggplot() + geom_blank() + 
        ggtitle("EVI2 for reference-data in Azraq (Jordan)") +
        ylab("EVI2") + xlab("month") +
        theme_bw(base_size = 12, base_family = "Times New Roman") + 
        geom_smooth(aes(x=Date, y=Vegetable_mean, ymin=Vegetable_min, 
            ymax=Vegetable_max, color="Vegetable", fill="Vegetable"),
            data=Grouped_Croptypes_EVI2, stat="identity") +
        geom_line(aes(x=Date, y=Tomato, color="Tomato"), data=Sample_EVI2_A_SPOT) +
        scale_fill_manual(name="Min-Max-Range and Mean \nof specific Croptypes",
            values=c(Vegetable="#008B00", Tomato="#FFFFFF")) +
        scale_color_manual(name="Min-Max-Range and Mean \nof specific Croptypes",
            values=c(Vegetable="#008B00",Tomato="#CD4F39"))
    EVI2_veg
    

    Note the addition of color= and fill= in the aes() calls. You really should put stuff you want in legends inside aes(). Here i specify "fake" colors that i then define them in the scale_*_manual commands.

    sample output

    0 讨论(0)
提交回复
热议问题