如何在ggridges的ridgeplot中添加垂直颜色渐变?

Vic*_*ths 7 r ggplot2 ggridges

ggridges包让你画ridgeplots有两种纯色:

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

或使用水平颜色渐变:

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")
Run Code Online (Sandbox Code Playgroud)

但是我想知道是否可以生成具有垂直颜色渐变的类似图表,例如本示例(使用D3.js绘制)。有没有办法在R中实现类似的东西?

来自ONS的D3.js中的垂直梯度ridgeplot

图片来源ONS:最有可能死于自杀和药物中毒的中年人

Vic*_*ths 5

我们可以使用devoutsvg和相关的svgpatternsimple包来做到这一点:

# 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())    
Run Code Online (Sandbox Code Playgroud)

这为您提供了一个具有垂直渐变的 .svg 文件,如下所示:垂直渐变填充脊线图。

在此处输入图片说明


更新:函数现在在GitHub 上:VictimOfMaths/DeathsOfDespair