[R language]-Kernel density estimation graph drawing

This issue introduces the use of R language ggplot2 package to draw kernel density estimation graphs.

Kernel Density Estimation (KDE) is used to estimate unknown density functions in probability theory. It is one of the non-parametric testing methods. It was proposed by Rosenblatt (1955) and Emanuel Parzen (1962), also known as Parzen window. (Parzen window). When analyzing the kernel density function, we mainly observe its area, not its value. The area enclosed by the vertical axis and the horizontal axis in the kernel density diagram is 1.

1 Data preparation

Data input format (csv format):

2 R package loading and data import

#下载包#

install.package("ggplot2")

#加载包#

library(ggplot2)

library(reshape2)

#数据载入#

data  = read.table(file = 'C:/Rdata/jc/density1.csv', sep = ',', header = T) #header=T表示数据中的第一行是列名,如果没有列名就用 header=F

# 转换数据成长数据格式(ggplot常用)

data = melt(data)            # melt为reshape2的函数

head(data)

If gene expression data or other needs log function processing, you can use the following code

#data=log10(data[,2]+0.0001) #加0.0001主要为了计算有0不好计算,2列进行计算;如有2到12列进行计算则用[,2:12]

#round(data,2)

#data=data.frame(data)

#head(data)

#write.csv(data,'C:/Rdata/jc/density1.csv') #数据导出

#write.table(data,'C:/Rdata/jc/density1.txt')

3 Density map drawing

#基础密度图绘制#

p = ggplot(data, aes(x =value))#x轴表示基因表达值,y轴表示频率就不需要指定

p + geom_density(color = "black", #线和点的颜色

                 fill = "gray") #填充颜色

Figure 1 Basic kernel density map

#美化-线条#

p + geom_density(aes(color = variable))#按照不同组改变线条颜色

 Figure 2 Unfilled kernel density map

#美化-填充#

p + geom_density(aes(fill = variable), #按照不同组改变填充颜色

                 alpha=0.5, #调整透明度

                 linetype = 1, # 线条类型1是实线,2是虚线

                 size=0.5    # 线条粗细

                 )  

# fill   指填充颜色

# color  指线和点的颜色

# colour 指图形边界颜色

Figure 3 Beautify + fill kernel density map

Okay, that’s it for this sharing.

Follow the official account and send the "kernel estimation density map" to get the complete code

Guess you like

Origin blog.csdn.net/weixin_54004950/article/details/128297224