Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot heatmap from points in R

Tags:

r

charts

heatmap

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.

like image 975
lbedogni Avatar asked Oct 14 '25 09:10

lbedogni


1 Answers

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

like image 59
lukeA Avatar answered Oct 17 '25 02:10

lukeA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!