R color scatter plot points based on values

后端 未结 4 1579
悲哀的现实
悲哀的现实 2020-11-28 08:03

I am able to plot a scatter plot and color the points based on one criteria, i.e. I can color all points >=3 as red and the remainder as black. I would love to be able to co

4条回答
  •  野性不改
    2020-11-28 08:38

    Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.

     # make a grid 'Grd' of points and number points for side of square 'GrdD'
    Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
    GrdD <- length(unique(Grd$Var1))
    
    # Add z-values to the grid points
    Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)
    
    # Make a vector of thresholds 'Brks' to colour code z 
    Brks <- c(seq(0,18,3),Inf)
    
    # Make a vector of labels 'Lbls' for the colour threhsolds
    Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')
    
    # Make a vector of colours 'Clrs' for to match each range
    Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")
    
    # Make up lookup dataframe 'LkUp' of the lables and colours 
    LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)
    
    # Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
    Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))
    
    # Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
    Grd <- merge(Grd,LkUp, by.x = 'Lbls')
    
    # Plot the grid using the 'Clrs' field for the colour of each point
    plot(Grd$Var1,
         Grd$Var2,
         xlim = c(0,400),
         ylim = c(0,400),
         cex = 1.0,
         col = Grd$Clrs,
         pch = 20,
         xlab = 'mX',
         ylab = 'mY',
         main = 'My Grid',
         axes = FALSE,
         labels = FALSE,
         las = 1
    )
    
    axis(1,seq(0,400,100))
    axis(2,seq(0,400,100),las = 1)
    box(col = 'black')
    
    legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')
    

提交回复
热议问题