I have generated a ggplot2 graph and I want to fill it showing the density of the points. I have managed it using the following formula for density:
get_density <- function(x, y, n = 250) {
dens <- MASS::kde2d(x = x, y = y, n = n)
ix <- findInterval(x, dens$x)
iy <- findInterval(y, dens$y)
ii <- cbind(ix, iy)
return(dens$z[ii])}
and then getting the density of the points in a new "density" column based on the formula, with "lfc" and "pval" being the x,y variables:
data.MA$density <- get_density(data.MA$pval, data.MA$lfc)
The ggplot object I am plotting is:
heatmap2 <- ggplot() +
geom_point(data = filter(data.MA, chg == "unchanged"),
aes(basemean, lfc, color = density)) +
geom_point(data = filter(data.MA, chg == "changed"),
aes(basemean, lfc, fill = dir),
shape = 21, size = 2, stroke = 0.1) +
scale_fill_manual(values = c("#FFA600", "#00B2FF", "#00B2FF")) +
scale_colour_gradient2(low = "blue", mid = "white", high = "red", midpoint = 10) +
theme_bw() + scale_y_continuous() + scale_x_continuous()
This gives me the following graph:
Here is a samples of the data.MA:
gene pval lfc basemean density dir peakid chg
1 NXT1 41.22403 3.58 9.50 3.339690e-02 increased 1 changed
2 BEND5 23.41567 5.03 8.01 0.000000e+00 increased 2 changed
3 PLB1 23.19450 7.91 8.13 4.849746e-78 increased 3 changed
4 LYRM9 20.81531 2.35 11.43 0.000000e+00 increased 4 changed
5 MIR4464 14.73049 3.65 7.99 0.000000e+00 increased 5 changed
6 HSD17B2 14.63451 4.51 7.31 0.000000e+00 increased 6 changed
My question is how can I make the gradient more disperse in the middle, so it is not just a red stripe in the middle and more of a gradient?
Can anyone suggest a different formula for the density perhaps?
Or a way to define the gradient better to be in more separate blocks?


