creating a more continuous color palette in r, ggplot2, lattice, or latticeExtra

后端 未结 3 551
野的像风
野的像风 2020-12-17 00:02

Warning.... very novice question follows:

I am trying to plot a fairly regular distribution of several thousand (X,Y) points each associated with a value, let\'s cal

相关标签:
3条回答
  • 2020-12-17 00:32

    Have you looked at scale_gradient in ggplot? Or scale_brewer for discrete colours? Here's an example of scale_gradient

    dat <- data.frame(x = rnorm(1000), y = rnorm(1000), z = sample(-20:20, 1000, TRUE))
    
    p <- ggplot(dat, aes(x, y, colour = z)) + geom_point() 
    p + scale_colour_gradient()
    p + scale_colour_gradient(low = "red", high = "blue")
    p + scale_colour_gradient2(low = "red", mid = "white", high = "blue")
    
    0 讨论(0)
  • 2020-12-17 00:36

    As far as lattice is concerned, you can set up your colors palette with RColorBrewer (or even colorspace). Using the example provided by @Chase, but with positive value for z:

    dat <- data.frame(x = rnorm(1000), y = rnorm(1000), z = sample(0:40, 1000, TRUE))
    library(RColorBrewer)
    # see, e.g.
    # display.brewer.all(9, type="seq")
    # display.brewer.pal(11, "RdBu")
    my.col <- colorRampPalette(brewer.pal(11, "RdBu"))(diff(range(dat$z)))
    xyplot(y ~ x, data=dat, col=my.col[dat$z], pch=19, alpha=.5)
    

    Note that it is also necessary here to increase the range of available colors by interpolation. Also, with levelplot(), you might want to play with cut= and pretty=.

    enter image description here

    0 讨论(0)
  • 2020-12-17 00:53

    The "concept" you are missing is the at argument to levelplot() which defines the breakpoints between colour levels and/or contour lines. The default is pretty(z) which results in only a few levels. You can set at to be a sequence covering the range of values you want.

    library(latticeExtra)
    
    dat <- data.frame(x = rnorm(1000), y = rnorm(1000), z = rnorm(1000, mean = 1))
    ## for centering the colour key around zero
    maxz <- max(abs(dat$z))
    
    levelplot(z ~ x * y, dat, at = seq(-maxz, maxz, length = 100), 
        panel = panel.levelplot.points, par.settings = custom.theme.2())
    
    0 讨论(0)
提交回复
热议问题