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
CodePudding user response:
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.