如何在ggplot的纵坐标中绘制带有不规则数据的热图?

时间:2016-05-30 15:20:11

标签: r ggplot2 heatmap

假设我想绘制以下数据:

# First set of X coordinates
x <- seq(0, 10, by = 0.2)
# Angles from 0 to 90 degrees
angles <- seq(0, 90, length.out = 10)
# Convert to radian
angles <- deg2rad(angles)
# Create an empty data frame
my.df <- data.frame()
# For each angle, populate the data frame
for (theta in angles) {
  y <- sin(x + theta)
  tmp <- data.frame(x = x, y = y, theta = as.factor(theta))
  my.df <- rbind(my.df, tmp)
}

x1 <- seq(0, 12, by = 0.3)
y1 <- sin(x1 - 0.5)
tmp <- data.frame(x = x1, y = y1, theta = as.factor(-0.5))
my.df <- rbind(my.df, tmp)

ggplot(my.df, aes(x, y, color = theta)) + geom_line()

这给了我一个很好的情节:

enter image description here

现在我想从这个数据集中绘制一张热图。有herethere教程可以使用geom_tile来执行此操作。

所以,试试吧:

# Convert the angle values from factors to numerics
my.df$theta <- as.numeric(levels(my.df$theta))[my.df$theta]
ggplot(my.df, aes(theta, x)) + geom_tile(aes(fill = y)) + scale_fill_gradient(low = "blue", high = "red")

Too bad

这不起作用,原因是我的x坐标没有相同的步骤:

x <- seq(0, 10, by = 0.2) vs x1 <- seq(0, 12, by = 0.3)

但是只要我使用相同的步骤x1 <- seq(0, 12, by = 0.2),就可以了:

Tada!

我现实生活中,我的数据集没有规则间隔(这些是实验数据),但我仍然需要将它们显示为热图。我该怎么办?

1 个答案:

答案 0 :(得分:2)

您可以使用akima将函数插值为适合热图图的形式。

library(akima)
library(ggplot2) 
my.df.interp <- interp(x = my.df$theta, y = my.df$x, z = my.df$y, nx = 30, ny = 30) 
my.df.interp.xyz <- as.data.frame(interp2xyz(my.df.interp))
names(my.df.interp.xyz) <- c("theta", "x", "y")

ggplot(my.df.interp.xyz, aes(x = theta, y = x, fill = y)) + geom_tile() + 
scale_fill_gradient(low = "blue", high = "red")

enter image description here

如果您希望使用其他分辨率,可以将nxny参数更改为interp

仅使用ggplot2执行此操作的另一种方法是使用stat_summary_2d

library(ggplot2)
ggplot(my.df, aes(x = theta, y = x, z = y)) + stat_summary_2d(binwidth = 0.3) + 
scale_fill_gradient(low = "blue", high = "red")

enter image description here