首页 > > > R语言可视化——直方图及其美化技巧!
数据集仍然使用上一节使用到的有关钻石的数据信息。
data(diamonds)
set.seed(42)
small <- diamonds[sample(nrow(diamonds), 1000), ]
head(small)
以上通过设定随机种子,从diamonds中随机抽取了1000个数据作为我们制作直方图的样本数据(源数据集有点大)。
直方图的做法与我们之前做柱形图(条型图)所使用函数主题语法大致相同,不同仅仅在于添加的图层对象为geom_histogram()
由于直方图呈现数据分布趋势,所以仅需一个数值型变量进入即可。
ggplot(small)+geom_histogram(aes(x=price))
ggplot(small,aes(price))+geom_histogram()
以上两句直方图语法是等价的,也就是说,无论参数price在ggplot函数中,还是在图层对象geom_histogram括号内,只要是被aes()美学映射包括着,都将作用于全局。
当然如果在直方图参数中添加颜色映射,那么就可以做出堆积直方图。
ggplot(small,aes(price,fill=cut))+geom_histogram()
当颜色变量(因子变量)进入aes内的时候,默认直方图输出为堆积直方图。(大家是否想起了之前学过的柱形图,可以通过设置position参数对多序列柱形进行堆积、簇状转换)。
我们尝试着将position=stack参数加入geom_histogram(position="stack")参数中,看下以上说法是否可靠。
ggplot(small,aes(price,fill=cut))+geom_histogram(position="stack")
果然不出所料,加入分类变量时的直方图,其位置调整与柱形图如出一辙,那么我们可以将position的几个参数挨个尝试:
ggplot(small,aes(price,fill=cut,alpha = 1/10))+
geom_histogram(position="identity")
#position=identity,即不对直方图位置作任何变换。
ggplot(small,aes(price,fill=cut,alpha = 1/10))+
geom_histogram(position="dodge")
#position=dodge,将各系列位置错开成簇状直方图。
ggplot(small,aes(price,fill=cut,alpha = 1/10))+
geom_histogram(position="fill")
#position=fill,将各系列位置错开成堆积百分比直方图。
以上就是关于直方图几种常用形式,接下来讲关于直方图图表元素调整。
直方图的binwidth参数控制直方图组距大小。
ggplot(diamonds, aes(carat))+geom_histogram(binwidth = 0.01)
ggplot(diamonds, aes(carat))+geom_histogram(binwidth = 0.2)
当然也可以在直方图中直接添加fill填充为喜欢的颜色。
ggplot(diamonds, aes(carat))+
geom_histogram(binwidth = 0.1,fill="steelblue")
使用外部主题命令:
ggplot(diamonds, aes(carat))+
geom_histogram(binwidth = 0.1)+
theme_stata()+
scale_fill_stata() #以上使用了stata的主题及配色模板
ggplot(diamonds, aes(carat))+
geom_histogram(binwidth = 0.1)+
theme_solarized()+
scale_fill_solarized() #以上使用了solarized主题及配色模板
手动自定义颜色:
ggplot(diamonds, aes(carat,fill="steelblue"))+
geom_histogram(binwidth = 0.1)+
theme_few()+
scale_fill_manual(values="#FB882C")+ theme(strip.background=element_blank(),legend.position="none") 
ggplot(small,aes(price,fill=cut))+
geom_histogram(position="fill") +
theme_wsj()+
scale_fill_wsj()+
theme(strip.background=element_blank(),legend.position="none")

ggplot(small,aes(price,fill=cut))+
geom_histogram(position="fill") +
theme_economist(base_size=14)+
scale_fill_economist()+
theme(strip.background=element_blank(),legend.position="none") 
关于直方图的分面技巧:
ggplot(small,aes(price,fill=cut))+
geom_histogram()+
facet_wrap(~cut)
ggplot(small,aes(price,fill=cut))+
geom_histogram()+
facet_wrap(~cut)+
theme_wsj()+
scale_fill_wsj()+
guides(fill=guide_legend(title=NULL))
#关于直方图的封面技巧
ggplot(small,aes(price,fill=cut))+
geom_histogram()+
facet_wrap(~cut)+
theme_economist(base_size=14)+
scale_fill_economist()+
guides(fill=guide_legend(title=NULL)) 
微信:ljty1991
博客主页:raindu's home
个人公众号:数据小魔方(datamofang)
团队公众号:EasyCharts
qq交流群:[魔方学院]553270834
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31537575/viewspace-3144349/ ,如需转载,请注明出处,否则将追究法律责任。