ggplot: colour points by groups based on user defined colours

后端 未结 3 1898
庸人自扰
庸人自扰 2020-12-01 13:05

I am trying to define the colours of groups of points plotted in ggplot. I adapted code from this post:

Color ggplot points based on defined color codes

but

相关标签:
3条回答
  • 2020-12-01 13:29

    It works if you use unique and as.character:

    ggplot(data = df, aes(col, D, colour = zone))+ 
      geom_point() +
      scale_colour_manual(breaks = df$zone, 
                          values = unique(as.character(df$color.codes)))
    

    enter image description here

    0 讨论(0)
  • 2020-12-01 13:30

    Sven beat me by a few secs, but slightly different:

    df.unique <- unique(df[, c("zone", "color.names")])
    p + scale_colour_manual(breaks = df.unique$zone, values = as.character(df.unique$color.names))
    
    0 讨论(0)
  • 2020-12-01 13:43

    You are somewhere between two different solutions.

    One approach is to not put the colors into the df data frame and specify the mapping between zone and desired color in the scale call:

    ggplot(data=df, aes(col, D, colour = zone))+ 
      geom_point() +
      scale_colour_manual(values=setNames(color.codes, zone))
    

    enter image description here

    Note that this does not use color.codes or color.names from df, nor does it use df2 directly (though it does use the columns that are used to make df2; if you have something like df2 and not the columns separately, you can use setNames(df2$color.codes, df2$zone) instead).

    The other approach maps color directly to the color codes and uses scale_color_identity, but then has to go through some additional labeling to get the legend right.

    ggplot(data=df, aes(col, D, colour = color.codes)) +
      geom_point() +
      scale_colour_identity("zone", breaks=color.codes, labels=zone, guide="legend")
    

    enter image description here

    The first is, in my opinion, the better solution.

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