WangJL2021 / scPolyA-seq

https://pubmed.ncbi.nlm.nih.gov/36454750/
2 stars 1 forks source link

density plot and bandwidth #1

Open WangJL2021 opened 3 years ago

WangJL2021 commented 3 years ago

1. Generate dataset

arr=c(0, 0, 0, 1, 1)
hist(arr)
plot( density( arr ) )

01

Density plot will overflow borders for smoothness, especially when extrema locate as borders, as demonstrated in this case.

2. Ggplot will cut the density curve at the border line.

library(ggplot2)

ggplot(data.frame(x=arr), aes(x))+
  geom_density()+
  theme_bw()

# same as 
plot( density( arr ), xlim=c(0,1) )

02

3. Peaks sharpen as the bandwidth decreases

By default, bandwidth will change according to the dataset.

plot( density( arr ) ) #default 0.35
plot( density( arr, bw=0.2 ), xlim=c(0, 1) )

03

draw3=function(bw=0.2){
  plot( density( arr, bw=bw ), xlim=c(0, 1), 
        main=paste0("bw=",bw),
        col="blue" )
}
pdf("a1.pdf", width=5, height=5)
par(mfrow=c(2,2))
draw3(0.2)
draw3(0.1)
draw3(0.01)
draw3(0.001)
dev.off()

a1

4. Cut the margin between y-axis to figure by setting xaxs ="i"

draw4=function(bw=0.2){
  plot( density( arr, bw=bw ), xlim=c(0, 1), 
        xaxs ='i', 
        main=paste0("xaxs ='i', bw=",bw),
        col="red")
}

pdf("a2.pdf", width=5, height=5)
par(mfrow=c(2,2))
draw4(0.2)
draw4(0.1)
draw4(0.01)
draw4(0.001)
dev.off()

a2

5. try ggplot2

draw5=function(bw=0.2){
  ggplot(data.frame(x=arr), aes(x))+
    geom_density(bw=bw, col="purple")+
    theme_bw()+
    labs(title= paste0("bw=",bw) )
}

g1=draw5(0.2); g1
g2=draw5(0.1); g2
g3=draw5(0.01); g3
g4=draw5(0.001); g4

library(gridExtra)

pdf("a5.pdf", width=4, height=4)
grid.arrange( g1, g2, g3, g4, nrow=2)
dev.off()

05

== end ==

DawnEve commented 10 months ago

6. try ggplot2 geom_violin()

arr=c(0, 0, 0, 1, 1)

library(ggplot2)

draw6=function(bw=0.2, isTrim=T){
  ggplot(data.frame(group=1, value=arr), aes(x=group, y=value)) + 
    geom_violin(bw=bw, trim=isTrim)+
    theme_bw(base_size = 12)+
    ggtitle( sprintf("bw=%s, trim=%s", bw, isTrim) )+
    theme(
      title = element_text(size=8)
    )
}

g1=draw6(0.1, F); g1
g2=draw6(0.01, F); g2

g3=draw6(0.1, T); g3
g4=draw6(0.01, T); g4

library(gridExtra)

pdf("a6.pdf", width=4, height=4)
grid.arrange( g1, g2, g3, g4, nrow=2)
dev.off()

# same as in 5, but on Y axis.