I would like to use ggplot to create multiple density plots that have the same data but that show a specific line highlighted. The table I have is extremely big but has the following columns:
Marker Sample value
X1 4_HVxLF 0.5
X2 4_HVxLF 0.1
...
.
ggplot(Dta, aes(x=value, group=Sample, color = Sample)) +
geom_density()+
xlab("value")+
ylab("Density")+
theme_classic()
It is not easy to interpret. Then, My aim is to get something like this: . The code used is:
ggplot(Dta, aes(x=value, group=Sample, color = Sample)) +
geom_density()+
xlab("value")+
ylab("Density")+
theme_classic()+
gghighlight(SampleName == "25_HVxLF",
unhighlighted_params = list(colour = "grey90"))
So I tried building a loop to get a PDF with 4 plots like the second one per page and for all my samples (105 of them). I cannot used facet_wrap
because there are too many of them.
Here is what I tried:
Samples <- unique(Dta$Sample)
pdf('Allplots.pdf', width = 8, height = 11)
par(mfrow=c(4,2))
for (i in Samples){
ggplot(Dta, aes(x=value, group=Sample,
color = Sample)) +
geom_density()+
xlab("value")+
ylab("Density")+
theme_classic()+
gghighlight(Sample == Samples[i],
unhighlighted_params = list(colour = "grey90"))
}
dev.off()
But the PDF that comes out is 4kb and I cannot open it. It says there are no pages. I am not used to work with loops so this is my first attempt ... I don't know what I did wrong (maybe many things), could someone help me figure out ?
Thank you in advance for your kind help !
Diana
Using
patchwork
andlapply
to loop over your samples one approach to achieve your desired result may look like so:patchwork::wrap_plots
Making use of some fake random example data:
DATA