Search code examples
rggplot2leading-zero

Removing leading zeros from a ggplot2 figure


I am trying to use ggplot to generate a heatmap of a correlation matrix without including leading zeros in the data.

Consider this example from LifeCycleSavings in the "datasets" package:

       pop75    dpi   ddpi
sr     0.317  0.220  0.305
pop15 -0.908 -0.756 -0.048

I can plot a heatmap like so:

library(reshape2)
melted_cors <- melt(cors)
library(ggplot2)
ggplot(melted_cors, aes(Var2, Var1, fill = value)) +
  geom_tile(color = "white") +
  geom_text(aes(Var2, Var1, label = value), color = "black", size = 4) +
  scale_fill_gradient2(low = "blue", mid = "white", high = "red",
                       midpoint = 0, limit = c(0,1), space = "Lab", 
                       name="Pearson\nCorrelation") +
  theme_minimal() +
  theme(title = element_blank(), legend.position="none") +
  coord_fixed()

Is there any way to strip the leading zeroes from this output?


Solution

  • Columns and rows may be reversed. Using gsub works but is not very elegant.

    cors <- read.table(text=
    "label  pop75    dpi   ddpi
    sr     0.317  0.220  0.305
    pop15 -0.908 -0.756 -0.048", header=TRUE)
    
    library(reshape2)
    melted_cors <- melt(cors)
    library(ggplot2)
    ggplot(melted_cors, aes(label, variable, fill = value)) +
      geom_tile(color = "white") +
      geom_text(aes(label, variable, label = gsub("0\\.", "\\.", value)), color = "black", size = 4) +
      scale_fill_gradient2(low = "blue", mid = "white", high = "red",
                           midpoint = 0, limit = c(0,1), space = "Lab", 
                           name="Pearson\nCorrelation") +
      theme_minimal() +
      theme(title = element_blank(), legend.position="none") +
      coord_fixed()
    

    enter image description here