从 ggplot2 图中删除前导零

Removing leading zeros from a ggplot2 figure

我正在尝试使用 ggplot 生成相关矩阵的热图,而不包括数据中的前导零。

考虑 "datasets" 包中 LifeCycleSavings 的这个例子:

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

我可以像这样绘制 heatmap:

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()

有没有办法从这个输出中去除前导零?

列和行可以颠倒。使用 gsub 可以,但不是很优雅。

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()