Color ggplot points based on defined color codes

前端 未结 1 1206
一个人的身影
一个人的身影 2021-01-23 00:08

Is it possible to used ggplot to color points based on predefinded standard color codes contained in the data frame?

Below is some sample data and code to help articulat

相关标签:
1条回答
  • 2021-01-23 00:17

    The line you claimed didn't work:

    df3$color.code.new <- ifelse(is.na(df3$color.codes), "#000000", df3$color.codes)
    

    works for me, although I think you missed a digit in one of your hex colors. Once you have that straightened out, you just want to use scale_colour_manual with something like this:

    tick  <- c("GE","APPL","GM","BTU","WMT","JPM","LUV")
    price <- c(22,900,20,22,80,31,35)
    volume<- c(300,500,100,107,400,300,325)
    df1 <- data.frame(ticker=tick, price=price, volume=volume)
    
    tick<-c("GE","APPL","GM","BTU","WMT")
    ccodes<-c("#3399FF", "#FF0000", "#CC00FF", "#993300", "#66CC00")
    cnames<-c("blue", "red", "purple", "brown", "green")
    df2=data.frame(ticker=tick, color.codes=ccodes, color.names=cnames)
    
    ## merge color specifcations into data
    df3 <-merge(df1,df2, by=("ticker"), all.x=TRUE, all.y=TRUE)
    df3$color.code.new <- ifelse(is.na(df3$color.codes), "#000000", df3$color.codes) 
    
    p <- ggplot(df3, aes(volume, price,colour = ticker))+ 
             geom_point() 
    p + scale_colour_manual(breaks = df3$ticker,values = df3$color.code.new)
    

    enter image description here

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