2 color heatmap in R with middle color anchored to a specific value

后端 未结 2 1228
青春惊慌失措
青春惊慌失措 2021-01-02 04:56

This heatmap image was generated in Excel but as I\'m trying to learn R I would like to know how to make a heatmap like that with R.

相关标签:
2条回答
  • 2021-01-02 05:02

    You can use ?scale_fill_gradientn

    gving you values:

      library(scales)
      heat.dat <- heat[0:10,0:10]
      dat <- expand.grid(var1=1:10, var2=1:10)
      dat$value <- melt(heat.dat)$value
      ggplot(dat, aes(x=var1,y=var2))+ 
            geom_tile(aes(fill = value),colour='white')+
            scale_fill_gradientn(colours=c("red","white","green"),
             values  = rescale(c(min(dat$value), 1000, max(dat$value)))
    

    enter image description here

    Using Lattice:

    with(dat,
    levelplot(round(value,0)~y*x, 
              dat, 
              panel=function(...) {
                     arg <- list(...)
                     panel.levelplot(...)
                     panel.text(arg$x, arg$y,arg$z)},
              scales = list(y = list(at=y,labels=y),
                            x = list(at=y,labels=y)),
              col.regions = colorRampPalette(c("red", "white", "green"),interpolate ='spline'))
    )
    

    enter image description here

    0 讨论(0)
  • 2021-01-02 05:09

    In addition to the answer and comments of / to agstudy, you can also use pure ggplot syntax and map the labels within the aes() via label:

        heat=structure(c(1000, 1087.658, 1181.599, 1319.012, 0, 0, 0, 0, 261.824,0, 0, 1000, 1361.953, 1405.954, 0, 0, 0, 0, 0, 1121.21, 0, 0,1000, 187.5215, 909.1927, 0, 0, 0, 0, 0, 0, 0, 0, 1000, 817.5097,0, 0, 0, 0, 0, 57.0317, 935.5829, 0, 0, 1000, 887.7498, 0, 0,0, 0, 709.3896, 854.511, 1102.159, 093.8854, 0, 1000, 0, 0,0, 0, 843.7676, 889.5042, 1147.13, 1195.7298, 1101.2891, 015.9835,1000, 0, 0, 0, 932.2801, 1091.461, 984.1374, 1077.0797, 1064.6516,1062.1668, 911.0699, 1000, 0, 0, 0, 929.1611, 969.0718, 1119.464,1037.1623, 1105.2163, 1026.1989, 834.8725, 1000, 0, 1016.7203,0, 058.3456, 1159.5207, 990.3974, 983.2319, 951.3572, 927.6802,795.6285, 1000), Dim  c(10L, 10L), .Dimnames = list(NULL, NULL))
    
        heat_melted = reshape2::melt(heat[10:0,0:10])
    
        ggplot(heat_melted, aes(Var2, Var1, label = round(value))) +   
        geom_tile(aes(fill = value),  colour = "white") +   
        scale_fill_gradientn(colours=c("red", "white", "green"), 
        values=rescale(c(min(heat_melted$value), 1000, max(heat_melted$value))), guide="colorbar") +
        geom_text()
    

    plot

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