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

时间:2019-10-23 14:56:27

标签: 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()

或具有水平的颜色渐变:

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")

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

Vertical gradient ridgeplot in D3.js from the ONS

图片来源ONS: Middle-aged generation most likely to die by suicide and drug poisoning

1 个答案:

答案 0 :(得分:4)

我们可以使用 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())    

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

enter image description here


更新:功能现已在GitHub: VictimOfMaths/DeathsOfDespair上。