I want to create a ggplot
heatmap in R
with the use of the command
ggplot()
geom_tile()
I have the following data
t_1 = c(-1,0,1,4)
t_2 = c(-2,-1,3)
W = c(1,10,3,4,17,9)
The t_1
corresponds to intervals in x-axis, i.e. corresponds to (-1,0)
, (0,1)
, (1,4)
. And t_2
to intervals in the y-axis, i.e. (-2,-1)
,(-1,3)
.
Based on these intervals a grid of 6 squares is created and on each square a value of W
corresponds. So the value W[1]
corresponds to the square (-1,0),(-2,-1)
, the value W[2]
corresponds to the square (-1,0),(-1,3)
etc.
So, how do I create that kind of heatmap??
CodePudding user response:
Here's a way that allows you to still use geom_tile
by using your vectors to provide the height
and width
aesthetics:
library(ggplot2)
d <- cbind(expand.grid(y = diff(t_2)/2 head(t_2, -1),
x = diff(t_1)/2 head(t_1, -1)), W)
ggplot(d, aes(x, y, fill = W))
geom_tile(height = rep(diff(t_2), 3), width = rep(diff(t_1), each = 2))
CodePudding user response:
You first have to create a data.frame containing the coordinates of your six squares. Afterwards you could plot your heat map using geom_rect
:
t_1 = c(-1,0,1,4)
t_2 = c(-2,-1,3)
W = c(1,10,3,4,17,9)
# Create a df containig coordinates of the squares
grid <- data.frame(
xmin = rep(rev(rev(t_1)[-1]), 2),
xmax = rep(t_1[-1], 2),
ymin = rep(rev(rev(t_2)[-1]), each = 3),
ymax = rep(t_2[-1], each = 3),
fill = W
)
grid
#> xmin xmax ymin ymax fill
#> 1 -1 0 -2 -1 1
#> 2 0 1 -2 -1 10
#> 3 1 4 -2 -1 3
#> 4 -1 0 -1 3 4
#> 5 0 1 -1 3 17
#> 6 1 4 -1 3 9
library(ggplot2)
ggplot(grid)
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill))