本文讲述如何利用ggplot2绘制密度图和直方图
准备数据:
set.seed(1126) #设置随机种子,让结果可重复
data <- rnorm(100) #生成100个符合正态分布的数字
min <- floor(min(data)) #这一串数字的最小值向下取整
max <- ceiling(max(data)) #这一串数字的最大值向上取整
range <- cut(data,breaks = seq(min,max,0.5)) #以0.5为间隔,分割数据
data <- as.data.frame(data)
text <- as.data.frame(summary(range)) #此数据框为geom_text做准备
text$x <- seq(min+0.25,max-0.25,0.5) #设置图中标记文本的横坐标
colnames(text)[1] <- "count"
text$prop <- proportions(text$count) #计算构成比
开始画图:
ggplot(data = data,aes(data,..density../2))+ # 纵坐标 = 频率/组距,我这里组距设置的是0.5,因此我又除以2,让纵坐标表示频率。
geom_density(size = 1.2,color = "skyblue")+ #设置颜色
geom_histogram(color = "yellow",fill = "deeppink",breaks = seq(min,max,0.5),alpha = 0.5)+
coord_cartesian(expand = F,xlim = c(min-0.2,max+0.2),ylim = c(0,max(text$prop)+0.02))+
scale_y_continuous(breaks = seq(0,0.5,0.05))+
scale_x_continuous(breaks = seq(min,max,1))+ #这两个函数设置坐标轴显示多少刻度点
labs(x = "",y = "Frequency")+
geom_text(data = text,aes(x,y = prop+0.005,label = prop))+
theme(panel.background = element_blank(),
panel.grid.major.y = element_line(colour = "grey",linetype = 2),
axis.line = element_line(colour = "black",size = rel(2),arrow = arrow(angle = 30,length = unit(0.1,"inches"))), #为坐标轴添加箭头
axis.title = element_text(size = rel(1.2)),
axis.text.x = element_text(size = rel(1.5),hjust = 1),
axis.text.y = element_text(hjust = 1,size = rel(1.5)),
axis.ticks = element_line(size = rel(1.5)),
plot.margin = margin(15,9,9,9))