change color for two geom_point() in ggplot2

后端 未结 2 1527
别跟我提以往
别跟我提以往 2020-12-31 06:59

Sample dataset:

library(ggplot2)    
df = read.table(text = 
              \"id      year    value1  value2 value3
            1           2000    1   2000           


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 07:23

    JLLagrange was on to the right idea. Use melt from reshape2 to convert your data to long form before plotting.

    df_long <- melt(df,id.vars = c("id", "year"), measure.vars=c("value2", "value3"))
    (p <- ggplot(df_long, aes(y = id)) + 
      scale_colour_manual(name = "", values = c(value3 = "grey", value2 = "black")) +
      scale_size_manual(name = "", values = c(value3 = 3, value2 = 5)) +
      geom_point(aes(x = value, colour = variable, size = variable))
    )
    

    In light of your comment, your data should be in a different form. Essentially, you are considering value2 and value3 to be the same as year, but with additional levels for value1. Reconstruct your data like this:

    df1 <- df[, c("id", "year", "value1")]
    
    df2 <- data.frame(
      id     = df$id,
      year   = df$value2,
      value1 = "4"
    )
    
    df3 <- data.frame(
      id     = df$id,
      year   = df$value3,
      value1 = "5"
    )
    
    df_all <- rbind(df1, df2, df3)
    df_all$value1 <- factor(df_all$value1)
    

    Then you can draw a plot with this:

    (p <- ggplot(df_all, aes(id, year, colour = value1)) + 
      geom_point(
        size = 3, 
        position = position_jitter(height = 0, width = 0.05)
      ) +
      scale_colour_manual(
        values = c("1" = "yellow", "2" = "orange", "3" = "red", "4" = "grey", "5" = "black")
      )
    )
    

    (I've added a bit of jitter to the points so you can see where they overlap. You could also set an alpha value in geom_point.)

提交回复
热议问题