打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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)

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
【R分享|实战】科白君浅谈ggplot2包学习逻辑
玩转单细胞(3):堆叠柱状图添加比例
《R数据科学》第1章-ggplot2图层与绘图大法-全
第一部分探索
一个对策,告别多图慎点!
如何用 R 绘制动态统计图?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服