lbedogni
lbedogni

Reputation: 7997

Plot heatmap from points in R

I want to plot a heatmap in R from a set of points.

I have a data frame like

X  Y  col
1  2  1
1  1  4
2  4  9
.......

I want to have a heatmap from this, with X and Y being the coordinates of the point, and col can be from 0 to 40. I tried to plot in points or using melt(), but with no luck.

I can plot some points with geom_point(), but I'd like to have a smooth transition from one color to another, some probably this is not the reight thing to do.

Upvotes: 4

Views: 5310

Answers (1)

lukeA
lukeA

Reputation: 54237

set.seed(1)
library(ggplot2)
df <- as.data.frame(expand.grid(1:50, 1:50))
df$col <- sample(0:40, size = nrow(df), replace = TRUE)
ggplot(df, aes(x = Var1, y = Var2, colour = col, fill = col )) + 
  geom_tile()

produces:

enter image description here

Edit:

And this

set.seed(1)
library(ggplot2)
df <- as.data.frame(expand.grid(1:50, 1:50))
df$col <- sample(0:40, size = nrow(df), replace = TRUE)
df <- df[sample(1:nrow(df), nrow(df) * .2, replace = FALSE), ]  # make holes
df <- df[rep(1:nrow(df), df$col), -3]
ggplot(df, aes(x = Var1, y = Var2)) + 
  geom_point() + 
  stat_density2d(aes(fill=..density..), geom = "tile", contour = FALSE) +
  scale_fill_gradient2(low = "white", high = "red")

produces

enter image description here

Upvotes: 6

Related Questions