Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a vertical colour gradient to a ridgeplot in ggridges?

The ggridges package lets you draw ridgeplots with either solid colour:

ggplot(iris, aes(x=Sepal.Width, y=Species))+
geom_density_ridges(alpha=0.33, scale=2, fill="#0570b0", colour=alpha(0.1))+
theme_classic()

or with horizontal colour gradients:

ggplot(iris, aes(x=Sepal.Width, y=Species, fill=..x..))+
geom_density_ridges_gradient(scale=2,colour=alpha(0.1))+
theme_classic()+
scale_fill_gradient(low="#0570b0", high="White")

But I want to know if it is possible to produce a similar chart with a vertical colour gradient, like this example (which was drawn using D3.js). Is there a way to implement something similar in R?

Vertical gradient ridgeplot in D3.js from the ONS

Image source ONS: Middle-aged generation most likely to die by suicide and drug poisoning

like image 599
VictimOfMaths Avatar asked Oct 23 '19 14:10

VictimOfMaths


1 Answers

We can do this using the devoutsvg and related svgpatternsimple packages:

# install packages    
# devtools::install_github("coolbutuseless/lofi")      
# devtools::install_github("coolbutuseless/minisvg")   
# devtools::install_github("coolbutuseless/devout")    
# devtools::install_github("coolbutuseless/devoutsvg") 
# devtools::install_github("coolbutuseless/poissoned") 

library(lofi)
library(minisvg)
library(devout)
library(devoutsvg)
library(svgpatternsimple)
library(poissoned)

#create gradient
grad <- create_gradient_pattern(id="p1", angle=90, colour1="White", 
colour2="#0570b0")

#visualise it
grad$show()

#encode it
gradRGB <- encode_pattern_params_as_hex_colour(pattern_name="gradient",angle=90, 
colour1="White", colour2="#0570b0")   

#draw graph
svgout(filename = "test.svg", pattern_pkg="svgpatternsimple")
ggplot(iris, aes(x=Sepal.Width, y=Species))+
  geom_density_ridges(alpha=0.33, scale=2, 
fill=gradRGB, colour=alpha(0.1))+
  theme_classic()
invisible(dev.off())    

This gives you an .svg file with a vertical gradient as that looks like this: Vertical gradient fill ridgeplot.

enter image description here


Update: Function is now on GitHub: VictimOfMaths/DeathsOfDespair.

like image 166
VictimOfMaths Avatar answered Sep 27 '22 18:09

VictimOfMaths