1

I have data that has two columns - date and values. I can create density plot with geom_density function. I would like to fill it with gradient color f.e. blue to red but I can't find how to do it. Anything I find on the internet requires Y value but I only have one variable.

Example of data:

Month_day; Temperature_anomaly
01-01;   -1.24
01-02;    0.31
01-03;    1.13
01-04;   -0.16

Code:

ggplot(data, aes(x = Temperature_anomaly)) + 
   geom_density() 

This creates simple density plot but have do I create single density plot and add gradient fill color based on the same value(Temperature_anomaly) to it?

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87

2 Answers2

2

You could precalculate the density and plot extremely thin columns to get a gradient effect. Adding a marginal rug plot along the x axis might be a nice touch to show the points on which your density is based:

library(tidyverse)

data %>%
  reframe(anomaly = density(Temperature_anomaly, n = 1000)$x,
          density = density(Temperature_anomaly, n = 1000)$y) %>%
  ggplot(aes(anomaly, density, fill = anomaly)) +
  geom_col(width = 0.05) +
  geom_line() +
  geom_vline(xintercept = 0, linetype = 2) +
  geom_rug(data = data, sides = "b", inherit.aes = FALSE,
           aes(x = Temperature_anomaly, color = Temperature_anomaly)) +
  scale_fill_gradient2(low = "blue", mid = "gray", high = "red") +
  scale_colour_gradient2(low = "blue", mid = "gray", high = "red", 
                         guide = "none") +
  labs(x = "Temperature Anomaly", y = "Probability density") +
  theme_minimal(base_size = 16)

enter image description here


Data used

set.seed(1)

data <- data.frame(Temperature_anomaly = rnorm(20, 1))
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

An alternative solution using the {ggridges} package:

set.seed(123)
data <- data.frame(Temperature_anomaly = rnorm(20))

library(ggridges)
ggplot(data, aes(x = Temperature_anomaly, y = 1, fill = after_stat(x))) + 
  geom_density_ridges_gradient()+
  scale_fill_gradient2(low="blue", mid = "white", high="red")

which gives:

density chart

nrennie
  • 1,877
  • 1
  • 4
  • 14