gpt4 book ai didi

r - ggplot2 每列的热图

转载 作者:行者123 更新时间:2023-12-04 17:08:48 24 4
gpt4 key购买 nike

我正在使用这个 R 脚本:

tableau <- read.table(
text =
"Net B C D E.(e) F.(f)
a 1.88 0.15 0.60 10.00 90.00
b 2.05 0.23 0.51 55.00 80.00
c 2.09 0.29 0.40 58.00 88.00
d 2.07 0.52 0.36 80.00 84.00
e 2.13 0.30 0.27 7.00 90.00",
header = TRUE)

library(plyr)
library(reshape)
library(ggplot2)
library(scales)
tableau.m <- melt(tableau)
tableau.m <- ddply(tableau.m, .(variable), transform, rescale = rescale(value))

(p <- ggplot(tableau.m, aes(variable, Net)) +
geom_tile(aes(fill = rescale), colour = "white") +
scale_fill_gradient(low = "white", high = "steelblue"))

base_size <- 9
p + theme_grey(base_size = base_size) +
labs(x = "", y = "") + scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
theme(legend.position = "none", axis.ticks = element_blank(),
axis.text.x = element_text(size = base_size * 0.8, angle = 0,
hjust = 0, colour = "grey50"))

tableau.s <- ddply(tableau.m, .(variable), transform, rescale = scale(value))

last_plot() %+% tableau.s

我得到了这个情节:

enter image description here

其中较深的蓝色表示较高的值,而白色表示较低的值。

如果可能,我如何更改此代码,以便:
  • 表格中的值显示在矩阵图的每个相应单元格中?
  • 热图的范围不是针对整个矩阵计算的,而是针对每一列计算的。那么,对于每个类别:B、C、D、E(e) 和 F(f),白色表示该列的较低值,深蓝色表示该列的较高值?

  • 谢谢!

    最佳答案

    添加 value作为每个单元格的文本标签,您可以使用 geom_text :

    p <- ggplot(tableau.m, aes(variable, Net)) + 
    geom_tile(aes(fill = rescale), colour = "white") +
    scale_fill_gradient(low = "white", high = "steelblue") +
    geom_text(aes(label=value))

    # Add the theme formatting
    base_size <- 9
    p + theme_grey(base_size = base_size) +
    labs(x = "", y = "") + scale_x_discrete(expand = c(0, 0)) +
    scale_y_discrete(expand = c(0, 0)) +
    theme(legend.position = "none", axis.ticks = element_blank(),
    axis.text.x = element_text(size = base_size * 0.8,
    angle = 0, hjust = 0, colour = "grey50"))

    对于您的第二个问题,您当前的代码已经解决了这个问题。变量 rescale分别缩放每一列,因为您已经执行了按 variable 分组的操作.自 rescalefill变量,为了设置颜色值,每列的值从零重新缩放到 1。您不需要 tableau.s ... last.plot...代码。

    下面是运行上面的代码后的图。请注意,在每一列中,最低值为白色,最高值为钢蓝色。 (您可能希望将边框颜色从“白色”更改为“gray90”,这样相邻的白色方块之间就会有边框):

    enter image description here

    关于r - ggplot2 每列的热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30040420/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com