我正在尝试使用ggplot生成相关矩阵的热图,而不在数据中包含前导零。
在“数据集”包中的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()
有没有办法从这个输出中删除前导零?
答案 0 :(得分:0)
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()