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()
這給了我一個很好的情節:
現在我想提請熱圖出這個數據集。有教程here和there這樣做使用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)
VS x1 <- seq(0, 12, by = 0.3)
但只要我使用相同的步驟x1 <- seq(0, 12, by = 0.2)
,它的工作原理:
我現實生活中,我的數據集不定時間隔(這是實驗數據),但我仍然需要將其顯示爲熱圖。我能怎麼做?
你有沒有一起來看看:http://stackoverflow.com/questions/7001710/how-can-i-force-ggplots-geom-tile-to-fill-every-方面? – bVa
geom_tile()使用數據中的最小步驟來確定切片的大小。您示例中的最小步驟很小,以至於瓷磚不再可見。所以你需要創建一個更粗糙的數據集。例如。通過舍入theta和x。或者將y的值插入粗糙網格。 – Thierry
@bVa現在正在看它。我嘗試過並且無法使其工作 – Ben