Search code examples
rggplot2tidyversegeom-textgeom-tile

Paste mean values on geom_tile plot (ggplot in R)


I am using this code:

 library(tidyverse)
 library(reshape)
 mtcars <- melt(mtcars, id="vs")
 mtcars$vs <- as.character(mtcars$vs)
 ggplot(mtcars, aes(x=vs, y=variable, fill=value)) + 
      geom_tile()

How can I paste the mean values as text on each tile? I tried + geom_text(mtcars, aes(vs, variable, label=mean)), but that does not work.

Also, how can I reverse the order of 0 and 1 on the x axis?


Solution

  • You can tweak stat_summary_2d() to display text based on computed variables with after_stat(). The order of the x-axis can be determined by setting the limits argument of the x-scale.

    suppressPackageStartupMessages({
      library(tidyverse)
      library(reshape)
      library(scales)
    })
    
    mtcars <- melt(mtcars, id="vs")
    mtcars$vs <- as.character(mtcars$vs)
    
    ggplot(mtcars, aes(x=vs, y =variable, fill = value)) +
      geom_tile() +
      stat_summary_2d(
        aes(z = value, 
            label = after_stat(number(value, accuracy = 0.01))),
        fun = mean,
        geom = "text"
      ) +
      scale_x_discrete(limits = c("1", "0"))
    

    Created on 2021-04-06 by the reprex package (v1.0.0)

    Also note that the geom_tile() just plots the last row of the dataset belonging to the x- and y-axis categories, so unless that is intended, it is something to be aware of.