How to generate a custom color scale for plotly heatmap in R

前端 未结 1 1864
失恋的感觉
失恋的感觉 2021-01-14 09:47

I would like to get a custom color scale which looks like for plotly heatmap (plot_ly(z = data, colors = customcolors, type = \"heatmap\"))

pale         


        
相关标签:
1条回答
  • 2021-01-14 10:30

    The code you use to generate a color palette works just fine. You only need to provide data that match with a heatmap. The following code provides this:

    library(RColorBrewer)
    library(plotly)
    
    # your palette definition
    palette <- colorRampPalette(c("darkblue", "blue", "lightblue1",
                                  "green","yellow", "red", "darkred"))
    
    set.seed(9876)    # for reproducibility
    
    ## a complete random set
    hmdata <- matrix(data = sample(x = 1:10^6, size = 100*100), nrow = 100, ncol = 100)
    plot_ly(z = hmdata, colors = palette(50), type = "heatmap")
    

    This gives the following heatmap:

    ## a random set that has been sorted
    hmdata_s <- matrix(data = sort(sample(x = 1:10^6, size = 100*100)), nrow = 100, ncol = 100)
    plot_ly(z = hmdata_s, colors = palette(50), type = "heatmap")
    

    Yielding this plot:

    Please let me know whether this is what you want.

    UPDATE

    you can set custom scale in plot_ly with zauto, zmax, and zmin. The following 2 pieces of code and graphs will illustrate this:

    The scale is set from 1 to 100 and the data vary similarly:

    hmdata_s3 <- matrix(data = sort(sample(x = 1:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
    plot_ly(z = hmdata_s3, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)
    

    The scale is set from 1 to 100 and the data vary between 50 and 100 only

    hmdata_s4 <- matrix(data = sort(sample(x = 50:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
    plot_ly(z = hmdata_s4, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)
    

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