Assign point color depending on data.frame column value R

后端 未结 1 575
一个人的身影
一个人的身影 2020-12-19 01:42

this is my first question on SO, I hope someone can help me answer it.

I\'m reading data from a csv with R with data<-read.csv(\"/data.csv\")

1条回答
  •  时光取名叫无心
    2020-12-19 02:22

    One way to do this, as suggested by help("scale_colour_manual") is to use a named character vector:

    col <- as.character(data$Color)
    names(col) <- as.character(data$Group)
    

    And then map the values argument of the scale to this vector

    # just showing the relevant line
    scale_color_manual(values=col) +
    

    full code

    xlim<-max(c(abs(min(data$x)),abs(max(data$x))))
    ylim<-max(c(abs(min(data$y)),abs(max(data$y))))
    
    col <- as.character(data$Color)
    names(col) <- as.character(data$Group)
    
    ggplot(data, aes(x = x, y = y, label = Group)) +
      geom_point(aes(size = size, colour = Group), show.legend = TRUE) +
      scale_color_manual(values=col) +
      geom_text(size = 4) +
      scale_size(range = c(5,15)) +
      scale_x_continuous(name="x", limits=c(xlim*-1-1,xlim+1))+
      scale_y_continuous(name="y", limits=c(ylim*-1-1,ylim+1))+
      theme_bw()
    

    Ouput:

    Data

    data <- read.table("Group    x   y  size    Color
    Medium   1   2  2000    yellow
    Small   -1   2  1000    red
    Large    2  -1  4000    green
    Other   -1  -1  2500    blue",head=TRUE)
    

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