继续“一图胜千言”系列,直方图(Histogram)又称柱状图,是由一系列高度不等的纵条纹表示数据分布情况,也可以展示数据的概率分布情况。
本文利用R语言的ggplot2包,从头带您绘制各式各样的直方图。
一 绘制基本直方图
准备数据及R包
library(ggplot2)
set.seed(1234)
df <- data.frame(sex = factor(rep(c("F", "M"),each=200)),weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5))) )
head(df)
sex weight
1 F 49
2 F 56
3 F 60
4 F 43
5 F 57
6 F 58
1.1 基本直方图
ggplot(df, aes(x=weight)) +
geom_histogram(binwidth=1,color="black",fill="white")# 改变 bins 和 颜色
1.2 添加均值线
ggplot(df, aes(x=weight)) +
geom_histogram(binwidth=1,color="black", fill="lightblue",linetype="dashed")+ #设置框线类型,颜色和fill的颜色
geom_vline(aes(xintercept=mean(weight)), color="blue", linetype="dashed", size=1) #添加均值线,设置线型,颜色等
1.3 添加密度曲线
ggplot(df, aes(x=weight)) +
geom_histogram(aes(y=..density..), colour="black", fill="white")+ # 需要密度形式
geom_density(alpha=.2, fill="#FF6666")
二 分组设置颜色 线型等
2.1 分组更改线型颜色
ggplot(df, aes(x=weight, color=sex)) +
geom_histogram(fill="white", alpha=0.5, position="identity")
其中position可选 “identity”, “stack”, “dodge”. 默认值是 “stack”.
2.2 分组添加均值线
library(plyr)
mu <- ddply(df, "sex", summarise, grp.mean=mean(weight))
p<-ggplot(df, aes(x=weight, color=sex)) +
geom_histogram(fill="white", position="dodge")+
geom_vline(data=mu, aes(xintercept=grp.mean, color=sex), linetype="dashed")+
theme(legend.position="top")
p
自定义颜色
# Use custom color palettes
p+scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))
# Use brewer color palettes
p+scale_color_brewer(palette="Dark2")
# Use grey scale
p + scale_color_grey() + theme_classic() + theme(legend.position="top")
分组更改fill的颜色
ggplot(df, aes(x=weight, fill=sex, color=sex)) + geom_histogram(binwidth=1,position="identity", alpha=0.5)+ geom_vline(data=mu, aes(xintercept=grp.mean),linetype="dashed")
三 汇总展示
ggplot(df, aes(x=weight, color=sex, fill=sex))+
geom_histogram(binwidth=1,aes(y=..density..), position="identity", alpha=0.5)+
geom_density(alpha=0.6)+
geom_vline(data=mu, aes(xintercept=grp.mean, color=sex),linetype="dashed")+
scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))+
scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"))+
labs(title="Weight histogram plot",x="Weight(kg)", y ="Density")+
theme_classic()
四 参考资料
ggplot2:数据分析与图形艺术
http://www.sthda.com/english/wiki/ggplot2-essentials
OK,输出基本图形后,根据自己的喜好进行细节的调整即可。