假设我要绘制以下数据:
# 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()
这给了我一个不错的情节:
现在,我想从该数据集中绘制一个热图。有教程这里和那里那些使用它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")
那是行不通的,原因是我的x坐标没有相同的步骤:
x <- seq(0, 10, by = 0.2)
与 x1 <- seq(0, 12, by = 0.3)
但是,只要我使用相同的步骤x1 <- seq(0, 12, by = 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")
如果您希望使用其他分辨率,则可以将nx
和ny
参数更改为interp
。
使用just的另一种方法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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句