ggplot2 add manual legend for two data series

前端 未结 1 1239
小蘑菇
小蘑菇 2021-01-28 07:28

I have this dataframe:

     Control    Stress days  sd_control  sd_stress
X1 0.9702100 0.9343627   X1 0.001900535 0.07035645
X2 0.9666619 0.8595523   X2 0.0149468         


        
相关标签:
1条回答
  • 2021-01-28 07:45

    The issue is that you use the color, fill and shape arguments.

    • To get a legend you have to map on aesthetics, i.e. inside aes().
    • After doing so ggplot will add lgends(s) automatically and you can apply scale_xxx_manual to get the desired colors, fill and shapes.
    • However, as this results in 3 legends (was not able to figure out why the merging of the legends failed) I use guides to keep only one of them and guide_legend to style the legend. Try this:
    library(ggplot2)
    library(scales)
    
    ggplot(my_data, aes(x=days, group=1)) +
      geom_errorbar(aes(ymax = Control-sd_control, ymin = Control+sd_control),
                    width=0.2, size=0.5) +
      geom_errorbar(aes(ymax = Stress-sd_stress, ymin = Stress+sd_stress),
                    width=0.2, size=0.5) +
      geom_point(aes(y=Control, color = "Control", fill = "Control", shape = "Control"), size=4) + 
      geom_line(aes(y=Control, color = "Control"),size=1) +
      geom_point(aes(y=Stress, color = "Stress", fill = "Stress", shape = "Stress"), size=4) +
      geom_line(aes(y=Stress, color = "Stress"), size=1) +
      geom_point(data=significance, aes(y=value),shape='*',size=6) +
      scale_color_manual(values = c("Control" = 'gray45', "Stress" = 'gray') ) +
      scale_fill_manual(values = c("Control" = 'gray45', "Stress" = 'gray') ) +
      scale_shape_manual(values = c("Control" = 23, "Stress" = 22)) +
      guides(shape = FALSE, fill = FALSE, 
             color = guide_legend(override.aes = list(shape =  c("Control" = 23, "Stress" = 22),
                                                      fill = c("Control" = 'gray45', "Stress" = 'gray')))) +
      labs(x='\nDAT',y='RWC\n') +
      scale_y_continuous(labels = percent_format(accuracy = 1),limits = c(0.5,1.04), 
                         expand = c(0,0), breaks = seq(from=0.5,to=1,by=0.05)) +
      scale_x_discrete(expand = c(0.07, 0), labels = c(0,7,14,21,27,35,42)) +
      ggtitle('Relative Water Content\n') +
      theme(panel.border = element_rect(colour = "black", fill=NA, size=0.5),
            panel.background = element_rect(fill = 'white'),
            plot.title = element_text(hjust = 0.5,family = 'Calibri',face='bold'),
            axis.title = element_text(family = 'Calibri',face = 'bold'),
            axis.text = element_text(family = 'Calibri')
      )
    

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