Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create several exposure combined density/ distribution plot in R

set.seed(42)
n=1000
db = data.frame(id=1:n,
                exp_1 = as.numeric(rnorm(n)),
                exp_2 = as.numeric(rnorm(n)),
                exp_3 = as.numeric(rnorm(n)), 
                exp_4=as.numeric(rnorm(n)))
label(db$exp_1)="Myx"
label(db$exp_2)="ff3"
label(db$exp_3)="poison-untitled"
label(db$exp_4)="NH3"

I want to create a combined density plot – with legends referring to the variable label
a plot similar to
enter image description here

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First you could change your data to a longer format using pivot_longer from tidyr. The graph you mentioned looks like ggpubr so you can use ggdensity with scale_fill_discrete to modify the legend like this:

set.seed(42)
n=1000
db = data.frame(id=1:n,
                exp_1 = as.numeric(rnorm(n)),
                exp_2 = as.numeric(rnorm(n)),
                exp_3 = as.numeric(rnorm(n)), 
                exp_4=as.numeric(rnorm(n)))

library(ggpubr)
library(tidyr)
library(dplyr)
db %>%
  pivot_longer(cols = -id) %>%
  ggdensity(x = 'value', fill = 'name') +
  scale_fill_discrete('', labels = c('Myx', 'ff3', 'poison-untitled', 'NH3'))

Created on 2022-12-03 with reprex v2.0.2


If you want to change the transparency, you could use the argument alpha in ggdensity. For more info check this documentation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading