I've got a data like below:
data_ex <- data.frame(x = runif(1000, 0, 10),
y = runif(1000, 0, 10),
z = runif(1000, 0, 1))
So basically these are points (x, y)
within a square (but could be also a rectangle) with some value z
. I want to divide this plane into 100 smaller squares (rectangles) and average z
value within them. So I did the following:
data_ex <- data_ex %>%
mutate(x2 = cut(x, breaks = 0:10),
y2 = cut(y, breaks = 0:10)) %>%
group_by(x2, y2) %>%
mutate(z = mean(z)) %>%
ungroup()
Now I want to plot it and use averaged z
value as colour of each small square (rectangle). Potentially, I could use geom_tile
to do it (like shown below), but it needs centers of the tiles as input.
data_ex %>%
ggplot() +
geom_rect(aes(xmin = 0, xmax = 10, ymin = 0, ymax = 10), fill = 'white') +
geom_tile(aes(x_center, y_center, fill = z))
I could probably extract it as a centers of x2
and y2
, but it seems a little cumbersome. Therefore, I wonder if there's quicker way to perform appropriate calculations or make desired plot in a different way.