简体   繁体   中英

Fit a line to a heat map

I have the following sample matrix:

m <- matrix(c(5,5,5,6,7,7,10,10,10,200,5,5,8,9,10,10,10,200,200,200,5,5,9,10,200,200,200,200,200,200,4,6,8,10,200,200,200,200,200,200,5,6,10,200,200,200,200,200,200,200,3,4,10,200,200,200,200,200,200,200,2,5,200,200,200,200,200,200,200,200,4,8,200,200,200,200,200,200,200,200,5,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200), nrow = 10, ncol = 10)

colnames(m) <- as.numeric(1:10)
rownames(m) <- as.numeric(10:1)

Matrix:

> m
     1   2   3   4   5   6   7   8   9  10
10   5   5   5   4   5   3   2   4   5 200
9    5   5   5   6   6   4   5   8 200 200
8    5   8   9   8  10  10 200 200 200 200
7    6   9  10  10 200 200 200 200 200 200
6    7  10 200 200 200 200 200 200 200 200
5    7  10 200 200 200 200 200 200 200 200
4   10  10 200 200 200 200 200 200 200 200
3   10 200 200 200 200 200 200 200 200 200
2   10 200 200 200 200 200 200 200 200 200
1  200 200 200 200 200 200 200 200 200 200

A heatmap of this data looks as follows:

library(ggplot2)
library(reshape2)

longData <- melt(m)

ggplot(longData, aes(x = Var1, y=Var2)) +
  geom_raster(aes(fill = value))

在此处输入图片说明

I would like to fit a curve to this heatmap.

Expected output 在此处输入图片说明

I have no idea how to address this problem. Is it possible to do this in R, and if so, how? In the end, I would like to be able to make a plot with just the curve (without the heatmap).

Something to get you started:

Data

library(tidyverse)
library(ggplot2)

line <- longData %>%
    filter(value != 200) %>%
    arrange(Var1, Var2) %>%
    group_by(Var1) %>%
    summarize(Var2 = max(Var2)) %>%
    bind_rows(tibble(Var1 = 0,
                     Var2 = 0))

Code

ggplot() +
    geom_raster(data = longData,
                aes(x = Var1, y = Var2, fill = value)) +
    geom_smooth(data = line,
                aes(x = Var1, y = Var2), 
                method = "loess", se = FALSE)

Result

结果

I extracted data from the heatmap as shown below, an made an equation search for equations with three or less parameters. A good candidate equation appears to be Scaled Power With Offset, "Var2 = a * pow(Var1, b) + Offset" woth parameters a = 3.2094504107129447E-02, b = 2.4442669641519590E+00, and Offset = 1.0648694513887436E+00 yielding RMSE = 0.383 and R-squared = 0.982.

点

情节

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM