ggplot2 heatmaps: using different gradients for categories

后端 未结 2 844

This Learning R blog post shows how to make a heatmap of basketball stats using ggplot2. The finished heatmap looks like this:

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 22:17

    Here's a simpler suggestion that uses ggplot2 aesthetics to map both gradients as well as color categories. Simply use an alpha-aesthetic to generate the gradient, and the fill-aesthetic for the category.

    Here is the code to do so, refactoring Brian Diggs' response:

    nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv")
    nba$Name <- with(nba, reorder(Name, PTS))
    
    library("ggplot2")
    library("plyr")
    library("reshape2")
    library("scales")
    
    nba.m <- melt(nba)
    nba.s <- ddply(nba.m, .(variable), transform,
               rescale = scale(value))
    
    nba.s$Category <- nba.s$variable
    levels(nba.s$Category) <- list("Offensive" = c("PTS", "FGM", "FGA", "X3PM", "X3PA", "AST"),
       "Defensive" = c("DRB", "ORB", "STL"),
       "Other" = c("G", "MIN", "FGP", "FTM", "FTA", "FTP", "X3PP", "TRB", "BLK", "TO", "PF"))
    

    Then, normalise the rescale variable to between 0 and 1:

    nba.s$rescale = (nba.s$rescale-min(nba.s$rescale))/(max(nba.s$rescale)-min(nba.s$rescale))
    

    And now, do the plotting:

    ggplot(nba.s, aes(variable, Name)) + 
      geom_tile(aes(alpha = rescale, fill=Category), colour = "white") + 
      scale_alpha(range=c(0,1)) +
      scale_x_discrete("", expand = c(0, 0)) + 
      scale_y_discrete("", expand = c(0, 0)) + 
      theme_grey(base_size = 9) + 
      theme(legend.position = "none",
            axis.ticks = element_blank(), 
            axis.text.x = element_text(angle = 330, hjust = 0)) +
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
    

    Note the use of alpha=rescale and then the scaling of the alpha range using scale_alpha(range=c(0,1)), which can be adapted to change the range appropriately for your plot.

提交回复
热议问题