1

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?

Sylvia Rodriguez
  • 1,203
  • 2
  • 11
  • 30

2 Answers2

2

You can do the processing work outside of ggplot to produce:

library(ggplot2)
library(dplyr)
library(tidyr)

df <- 
  mtcars %>%
  pivot_longer(-vs) %>% 
  group_by(vs, name) %>% 
  mutate(vs = factor(vs, levels = c(1, 0), ordered = TRUE),
         mean = round(mean(value), 2))


ggplot(df, aes(x=vs, y=name, fill=value)) + 
  geom_tile() +
  geom_text(aes(vs, name, label=mean), colour = "white", check_overlap = TRUE)  

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

Peter
  • 11,500
  • 5
  • 21
  • 31
1

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.

teunbrand
  • 33,645
  • 4
  • 37
  • 63