Search code examples
rplotggplot2heatmapdensity-plot

3-variables plotting heatmap ggplot2


I'm currently working on a very simple data.frame, containing three columns:

x contains x-coordinates of a set of points,

y contains y-coordinates of the set of points, and

weight contains a value associated to each point;

Now, working in ggplot2 I seem to be able to plot contour levels for these data, but i can't manage to find a way to fill the plot according to the variable weight. Here's the code that I used:

ggplot(df, aes(x,y, fill=weight)) + 
  geom_density_2d() +
  coord_fixed(ratio = 1) 

You can see that there's no filling whatsoever, sadly. I've been trying for three days now, and I'm starting to get depressed.

Specifying fill=weight and/or color = weight in the general ggplot call, resulted in nothing. I've tried to use different geoms (tile, raster, polygon...), still nothing. Tried to specify the aes directly into the geom layer, also didn't work. Tried to convert the object as a ppp but ggplot can't handle them, and also using base-R plotting didn't work. I have honestly no idea of what's wrong! I'm attaching the first 10 points' data, which is spaced on an irregular grid:

x = c(-0.13397460,-0.31698730,-0.13397460,0.13397460,-0.28867513,-0.13397460,-0.31698730,-0.13397460,-0.28867513,-0.26794919)

y = c(-0.5000000,-0.6830127,-0.5000000,-0.2320508,-0.6547005,-0.5000000,-0.6830127,-0.5000000,-0.6547005,0.0000000)

weight = c(4.799250e-01,5.500250e-01,4.799250e-01,-2.130287e+12,5.798250e-01,4.799250e-01,5.500250e-01,4.799250e-01,5.798250e-01,6.618956e-01)

any advise? The desired output would be something along these lines:

click

Thank you in advance.


Solution

  • From your description geom_density doesn't sound right.

    You could try geom_raster:

    ggplot(df, aes(x,y, fill = weight)) + 
         geom_raster() +
         coord_fixed(ratio = 1)  + 
         scale_fill_gradientn(colours = rev(rainbow(7)) # colourmap