0

If I am making a stat_density_2d plot, with raster geometry, how can I color one part of the chart one color, another part of the chart another?

So for this chart:

d <- ggplot(data, aes(xVal, yVal))
d + stat_density_2d(geom = "raster", aes(fill = ..density..), contour = FALSE) +
  scale_fill_gradient2(low = "white",
  high = "#1A6AFF", space = "Lab", limits=c(0.00000, 0.00008), guide = "colourbar") +
 geom_point() + xlim(-100,100)

How might I fill between -100 and 0 from a white to red gradient, and the 0 to 100 part of the plot with a white to blue gradient? Note that the fill is based on density, so it would just be splitting the chart into two parts, not creating a continuous scale along -100 to 100.

Union find
  • 7,759
  • 13
  • 60
  • 111
  • 1
    Please share your data using `dput()`. See more here: [How to make a great R reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Tung Apr 24 '18 at 14:21
  • See my post below. If this is not enough to get you going, please share your data. – Stan Apr 24 '18 at 22:07
  • @Stan It's not quite what i need, no. Basically, I want to split the chart into two panes. From xlim(-100 to 0) I want to use one color scale. From xlim(0 to 100) I want to use another. – Union find Apr 25 '18 at 01:52

1 Answers1

0

I believe what you are trying to accomplish is covered in the documentation. Here is the excerpt that uses the diamonds data set:

set.seed(4393)
dsmall <- diamonds[sample(nrow(diamonds), 1000), ]
d <- ggplot(dsmall, aes(x, y))
# If you map an aesthetic to a categorical variable, you will get a
# set of contours for each value of that variable
d + geom_density_2d(aes(colour = cut))

This produces the plot: enter image description here

If you want to turn off the contours for a tile image, you can do so:

# If we turn contouring off, we can use use geoms like tiles:
d + stat_density_2d(geom = "raster", aes(fill = ..density..), contour = FALSE)

Which produces the following plot: enter image description here

Stan
  • 905
  • 9
  • 20