Order of factor levels changes when plotting layers with data subsets

前端 未结 2 1787
滥情空心
滥情空心 2021-02-14 02:26

I am trying to control the order of items in a legend in a ggplot2 plot in R. I looked up some other similar questions and found out about changing the order of the

2条回答
  •  天涯浪人
    2021-02-14 02:46

    One possibility is to add a geom_blank as a first layer in the plot. From ?geom_blank: "The blank geom draws nothing, but can be a useful way of ensuring common scales between different plots.". We tell the geom_blank layer to use the entire data set. This layer thus sets up a scale which includes all levels of 'Month', correctly ordered. Then add the two layers of geom_pointrange, which each uses a subset of the data.

    Perhaps a matter of taste in this particular case, but I tend to prefer to prepare the data sets before I use them in ggplot.

    df_sum <- testdata[testdata$Month %in% c("June", "July"), ]
    df_win <- testdata[testdata$Month %in% c("December", "January"), ]
    
    ggplot(data = testdata, aes(x = hour, y = avg_hou, ymin = lower_ci, ymax = upper_ci,
           color = Month, shape = Month)) +
      geom_blank() +
      geom_pointrange(data = df_sum, size = 1, position = position_dodge(width = 0.3)) +
      geom_pointrange(data = df_win, size = 1, position = position_dodge(width = 0.6)) +
      scale_color_manual(values = c("June" = "#FDB863", "July" = "#E66101",
                         "December" = "#92C5DE", "January" = "#0571B0"))
    

    enter image description here

提交回复
热议问题