1

My data looks like this:

var1, var2, mean, std
1    , 2   , 3   , 4
etc..

I want to plot these into a heat map that looks like this one but I want to add text labels inside each cell, in this style: mean±std (i.e. mean plus minus error). in above case, the value in the cell would be 3±4 for var1 column = 1 and var2 row = 2, and similarly different values for other cells.

It's not important that it is a heatmap, it could be the label to a point or to a bar, i just want to generate the labels so that I get the strings "mean±std" for each label: 3±4. In my case, I will be making a heatmap where the colors are based on the value of mean, such as in here: https://stackoverflow.com/a/14290705/1504411

Thank you!

Community
  • 1
  • 1
newmathwhodis
  • 3,209
  • 2
  • 24
  • 26

3 Answers3

4

You can use plotmath in geom_text by setting parse = TRUE. Based on @beetroot's answer:

ggplot(dat) +
  geom_text(aes(x = 1, y = 2.5, 
                label = paste(mean, std, sep = "%+-%")), 
            parse = TRUE)
Roland
  • 127,288
  • 10
  • 191
  • 288
3

You can create labels with geom_text and paste the mean and sd values with the plus-minus-sign as the seperator (\u00B1 is the respective unicode):

dat <- data.frame(var1 = 1, var2 = 2, mean = 3, std = 4)

ggplot(dat) +
  geom_text(aes(x = 1, y = 2.5, label = paste(mean, std, sep = "\u00B1")))
erc
  • 10,113
  • 11
  • 57
  • 88
2

Thanks to beetroot's and Roland's answer this was my final code that worked (plus some bells and whistles):

p1 <- ggplot(r_output, aes(var1, var2)) + 
    geom_tile(aes(fill = mean))+
    geom_text(aes(fill = mean, label = paste(round(mean, 2), round(std, 2), sep = "\u00B1")), size = 2)+            
    scale_fill_gradient(low = "red", high = "blue") +
newmathwhodis
  • 3,209
  • 2
  • 24
  • 26