我正在使用ggplot2在R中制作热图,并且我想更改图块的大小,因为热图中的文本不适合单元格。以下是我的数据和尝试图。
library("ggplot2")
s = sprintf("dataset number %s", 1:9)
vars = sprintf("many many words here, here and here %s", 1:6)
data = data.frame(s = rep(s, 6), stringsAsFactors = FALSE)
data$variable = rep(vars, rep.int(9, 6))
data$variable = as.factor(data$variable)
data$value = rep.int(-1000, 54)
data$font = "plain"
for(v in (unique(data$s))) {
ids = which(data$s %in% "dataset number 1")
vals = data[ids, ]
row = rownames(vals[vals$value %in% max(vals$value, na.rm = TRUE), ])
data[row, ]$font = "bold"
}
我正在制作这样的热图
title = "Heatmap"
cbbPalette = list(grey = "#999999", black = "#000000", orange = "#E69F00", sky = "#56B4E9", green = "#009E73", yellow = "#F0E442", blue = "#0072B2", darko = "#D55E00",
pink = "#CC79A7")
pdf(sprintf("./heatmap.pdf"))
heatmap = ggplot(data = data, aes(x = variable, y = s, fill = value)) +
geom_tile(color = "black") +
scale_fill_gradient2(low = cbbPalette$pink, high = cbbPalette$green, mid = cbbPalette$grey,
midpoint = 0, limit = c(-100,100), space = "Lab",
name=title) +
scale_x_discrete(limits = levels(data$variable)) +
geom_vline(xintercept = 6 - 0.5, color = "white", size = 1) +
geom_vline(xintercept = 2 + 0.5, color = "white", size = 1) +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, vjust = 1,
size = 16, hjust = 1), legend.title = element_text(size = 18),
axis.text.y = element_text(size = 16)) +
coord_fixed()
#add numbers to cells
heatmap = heatmap + geom_text(aes(x = variable, y = s, label = value, fontface = font), color = cbbPalette$black, size = 3) +
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.ticks = element_blank(),
legend.justification = c(0.5, 0),
legend.direction = "horizontal",
legend.position = "top") +
guides(fill = guide_colorbar(barwidth = 7, barheight = 1,
title.position = "top", title.hjust = 0.5))
# Print the heatmap
print(heatmap)
dev.off()
我得到以下结果-heatmap
其他SO帖子建议在geom_tile
内更改宽度和高度,但我得到以下结果:
heatmap = ggplot(data = data, aes(x = variable, y = s, fill = value)) +
geom_tile(color = "black", aes(width = 2L)) + ...
我还尝试了更改geom_tile
和coord_fixed(ratio = 1L)
的高度,但没有成功。
另外,我知道我可以简单地更改文本的大小和数字即可,但是我需要保持字体大小不变。我也可以缩短标签,但假设这不是一个选择。
对此我将不胜感激。