R的ggplot2包画柱状图?
测试开头
测试结尾
笔者邀请您,先思考:
1 柱状图有什么作用?如何画柱状图?
柱状图(Bar chart)是使用不同长度的柱子来显示数据分布的图形。
一 基本柱状图1
描述因子类型的单个变量的数据分析
# 加载R包
library(ggplot2)
# 数据集 使用R语言内置的mtcars数据集
# 基本柱状图
ggplot(mtcars, aes(x=as.factor(cyl) )) +
geom_bar()
图形结果:
二 基本柱状图2
描述一个离散变量和一个连续变量的关系时,采用柱状图需要指定参数: stat=”identity”
# 创建数据集
data <- data.frame(name=c("A","B","C","D","E") , value=c(3,12,5,18,45))
# 绘制柱状图
ggplot(data, aes(x=name, y=value)) +
geom_bar(stat = "identity")
图形结果:
三 修改柱状图中柱子的颜色
可以通过以下方法来装饰柱子的颜色,从而让柱子更有鲜明对比性
# 1: 统一的颜色。颜色是用于边框,填充是用于内部
ggplot(mtcars, aes(x=as.factor(cyl) )) +
geom_bar(color="blue", fill=rgb(0.1,0.4,0.5,0.7) )
# 2: 使用色调
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +
geom_bar( ) +
scale_fill_hue(c = 40)
# 3: 使用RColorBrewer
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +
geom_bar( ) +
scale_fill_brewer(palette = "Set1")
# 4: 使用greyscale:
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + geom_bar( ) +
scale_fill_grey(start = 0.25, end = 0.75)
# 5: 设置 manualy
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + geom_bar( ) +
scale_fill_manual(values = c("red", "green", "blue") )
第3种方法的图形结果:
四 删除图例和添加坐标轴名称
# 删除图例和添加坐标轴名称
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +
geom_bar( ) +
theme(legend.position = "none") +
labs(x = "My class", y = "Value")
图形结果:
五 柱状图水平摆放
# 柱状图水平摆放
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +
geom_bar() +
coord_flip()
图形结果:
六 自定义柱子的宽度
# 自定义柱子的宽度
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl))) +
geom_bar(width=0.4)
图形结果:
七 分组柱状图
在基本柱状图的基础上,根据实际数据的情况,设计和实现分组柱状图,分组柱状图包括平铺和堆叠,而堆叠柱状图又可以分为堆叠数量或者堆叠百分比。
# 加载ggplot2包
library(ggplot2)
# 创建数据集
specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
set.seed(360)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)
# 1 分组柱状图
ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar(position="dodge", stat="identity")
# 2 堆叠柱状图
ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar( stat="identity")
# 3 堆叠柱状图百分比
ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar( stat="identity", position="fill")
分组柱状图结果:
堆叠柱状图结果:
堆叠柱状图百分比结果:
八 使用分面替代分组柱状图
使用faceting可以很好地替代分组柱状图。
# 分面柱状图
ggplot(data, aes(y=value, x=specie, color=specie, fill=specie)) +
geom_bar( stat="identity") +
facet_wrap(~condition)
公众号推荐:数据人才(ID:datarencai)
内容推荐
请关注“恒诺新知”微信公众号,感谢“R语言“,”数据那些事儿“,”老俊俊的生信笔记“,”冷🈚️思“,“珞珈R”,“生信星球”的支持!