2016-05-30 150 views
0

假設我想繪製以下數據:如何在ggplot的縱座標中繪製不規則數據的熱圖?

# 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

你有沒有一起來看看:http://stackoverflow.com/questions/7001710/how-can-i-force-ggplots-geom-tile-to-fill-every-方面? – bVa

+0

geom_tile()使用數據中的最小步驟來確定切片的大小。您示例中的最小步驟很小,以至於瓷磚不再可見。所以你需要創建一個更粗糙的數據集。例如。通過舍入theta和x。或者將y的值插入粗糙網格。 – Thierry

+0

@bVa現在正在看它。我嘗試過並且無法使其工作 – Ben

回答

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