使用geom_bar()函数绘制条形图,条形图的高度通常表示两种情况之一:每组中的数据的个数,或数据框中列的值,高度表示的含义是由geom_bar()函数的参数stat决定的,stat在geom_bar()函数中有两个有效值:count和identity。默认情况下,stat="count",这意味着每个条的高度等于每组中的数据的个数,并且,它与映射到y的图形属性不相容,所以,当设置stat="count"时,不能设置映射函数aes()中的y参数。如果设置stat="identity",这意味着条形的高度表示数据数据的值,而数据的值是由aes()函数的y参数决定的,就是说,把值映射到y,所以,当设置stat="identity"时,必须设置映射函数中的y参数,把它映射到数值变量。

geom_bar()函数的定义是:

geom_bar(mapping = NULL, data = NULL, stat = "count", width=0.9, position="stack")

参数注释:

  • stat:设置统计方法,有效值是count(默认值) 和 identity,其中,count表示条形的高度是变量的数量,identity表示条形的高度是变量的值;
  • position:位置调整,有效值是stack、dodge和fill,默认值是stack(堆叠),是指两个条形图堆叠摆放,dodge是指两个条形图并行摆放,fill是指按照比例来堆叠条形图,每个条形图的高度都相等,但是高度表示的数量是不尽相同的。
  • width:条形图的宽度,是个比值,默认值是0.9
  • color:条形图的线条颜色
  • fill:条形图的填充色

关于stat参数,有三个有效值,分别是count、identity和bin:

  • count是对离散的数据进行计数,计数的结果用一个特殊的变量..count.. 来表示,
  • bin是对连续变量进行统计转换,转换的结果使用变量..density..来表示
  • 而identity是直接引用数据集中变量的值

position参数也可以由两个函数来控制,参数vjust和widht是相对值:

position_stack(vjust = , reverse = FALSE)
position_dodge(width = NULL)
position_fill(vjust = , reverse = FALSE)

本文使用vcd包中的Arthritis数据集来演示如何创建条形图。

head(Arthritis)
ID Treatment Sex Age Improved
Treated Male Some
Treated Male None
Treated Male None
Treated Male Marked
Treated Male Marked
Treated Male Marked

其中变量Improved和Sex是因子类型,ID和Age是数值类型。

一,绘制基本的条形图

使用geom_bar()函数绘制条形图,

ggplot(data=ToothGrowth, mapping=aes(x=dose))+
geom_bar(stat="count")

当然,我们也可以先对数据进行处理,得到按照Improved进行分类的频数分布表,然后使用geom_bar()绘制条形图:

mytable <- with(Arthritis,table(Improved))
df <- as.data.frame(mytable) ggplot(data=df, mapping=aes(x=Improved,y=Freq))+
geom_bar(stat="identity")

绘制的条形图是相同的,如下图所示:

二,修改条形图的图形属性

条形图的图形属性包括条形图的宽度,条形图的颜色,条形图的标签,分组和修改图例的位置等。

1,修改条形图的宽度和颜色

把条形图的相对宽度设置为0.5,线条颜色设置为red,填充色设置为steelblue

ggplot(data=Arthritis, mapping=aes(x=Improved))+
geom_bar(stat="count",width=0.5, color='red',fill='steelblue')

2,设置条形图的文本

使用geom_text()为条形图添加文本,显示条形图的高度,并调整文本的位置和大小。

当stat="count"时,设置文本的标签需要使用一个特殊的变量 aes(label=..count..), 表示的是变量值的数量。

ggplot(data=Arthritis, mapping=aes(x=Improved))+
geom_bar(stat="count",width=0.5, color='red',fill='steelblue')+
geom_text(stat='count',aes(label=..count..), vjust=1.6, color="white", size=3.5)+
theme_minimal()

当stat="identity"时,设置文本的标签需要设置y轴的值,aes(lable=Freq),表示的变量的值。

mytable <- with(Arthritis,table(Improved))
df <- as.data.frame(mytable) ggplot(data=df, mapping=aes(x=Improved,y=Freq))+
geom_bar(stat="identity",width=0.5, color='red',fill='steelblue')+
geom_text(aes(label=Freq), vjust=1.6, color="white", size=3.5)+
theme_minimal()

添加文本数据之后,显示的条形图是:

3,按照分组修改条形图的图形属性

把条形图按照Improved变量进行分组,设置每个分组的填充色,这通过aes(fill=Improved)来实现,每个分组的填充色依次是scale_color_manual()定义的颜色:

ggplot(data=Arthritis, mapping=aes(x=Improved,fill=Improved))+
geom_bar(stat="count",width=0.5)+
scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))+
geom_text(stat='count',aes(label=..count..), vjust=1.6, color="white", size=3.5)+
theme_minimal()

4,修改图例的位置

修改图例的位置,通过theme(legend.position=) 来实现,默认的位置是right,有效值是right、top、bottom、left和none,其中none是指移除图例。

p <- ggplot(data=Arthritis, mapping=aes(x=Improved,fill=Improved))+
geom_bar(stat="count",width=0.5)+
scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))+
geom_text(stat='count',aes(label=..count..), vjust=1.6, color="white", size=3.5)+
theme_minimal() p + theme(legend.position="top")
p + theme(legend.position="bottom")
# Remove legend
p + theme(legend.position="none")

5,修改条形图的顺序

通过scale_x_discrete()函数修改标度的顺序:

p <- ggplot(data=Arthritis, mapping=aes(x=Improved,fill=Improved))+
geom_bar(stat="count",width=0.5)+
scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))+
geom_text(stat='count',aes(label=..count..), vjust=1.6, color="white", size=3.5)+
theme_minimal() p + scale_x_discrete(limits=c("Marked","Some", "None"))

三,包含分组的条形图

分组的条形图如何摆放,是由geom_bar()函数的position参数确定的,默认值是stack,表示堆叠摆放、dodge表示并行摆放、fill表示按照比例来堆叠条形图。

1,堆叠摆放

设置geom_bar()的position参数为"stack",在向条形图添加文本时,使用position=position_stack(0.5),调整文本的相对位置。

ggplot(data=Arthritis, mapping=aes(x=Improved,fill=Sex))+
geom_bar(stat="count",width=0.5,position='stack')+
scale_fill_manual(values=c('#999999','#E69F00'))+
geom_text(stat='count',aes(label=..count..), color="white", size=3.5,position=position_stack(0.5))+
theme_minimal()

2,并行摆放

调整y轴的最大值,使用position=position_dodge(0.5),vjust=-0.5 来调整文本的位置

y_max <- max(aggregate(ID~Improved+Sex,data=Arthritis,length)$ID)

ggplot(data=Arthritis, mapping=aes(x=Improved,fill=Sex))+
geom_bar(stat="count",width=0.5,position='dodge')+
scale_fill_manual(values=c('#999999','#E69F00'))+
ylim(,y_max+)+
geom_text(stat='count',aes(label=..count..), color="black", size=3.5,position=position_dodge(0.5),vjust=-0.5)+
theme_minimal()

 3,按照比例堆叠条形图

需要设置geom_bar(position="fill"),并使用geom_text(position=position_fill(0.5))来调整文本的位置,如果geom_text(aes(lable=..count..)),那么表示文本显示的值是变量的数量:

ggplot(data=Arthritis, mapping=aes(x=Improved,fill=Sex))+
geom_bar(stat="count",width=0.5,position='fill')+
scale_fill_manual(values=c('#999999','#E69F00'))+
geom_text(stat='count',aes(label=..count..), color="white", size=3.5,position=position_fill(0.5))+
theme_minimal()

该模式最大的特点是可以把文本显示为百分比:

ggplot(data=Arthritis, mapping=aes(x=Improved,fill=Sex))+
geom_bar(stat="count",width=0.5,position='fill')+
scale_fill_manual(values=c('#999999','#E69F00'))+
geom_text(stat='count',aes(label=scales::percent(..count../sum(..count..)))
, color="white", size=3.5,position=position_fill(0.5))+
theme_minimal()

四,增加注释和旋转坐标轴

在绘制条形图时,需要动态设置注释(annotate)的位置x和y,x和y的值是由条形图的高度决定的,

annotate(geom="text", x = NULL, y = NULL)

在绘制条形图时,可以动态设置x和y的大小:

library("ggplot2")
library("dplyr")
library("scales") #win.graph(width=, height=,pointsize=) #data
df <- data.frame(
rate_cut=rep(c("0 Change", "0 - 10", "10 - 20", "20 - 30", "30 - 40","40 - 50", "50 - 60", "60 - 70","70 - 80", "80 - 90", "90 - 100", ">100"),)
,freq=c(,,,,,,,,,,,,
,,,,,,,,,,,)
,product=c(rep('ProductA',),rep('ProductB',))
) #set order
labels_order <- c("0 Change", "0 - 10", "10 - 20", "20 - 30", "30 - 40","40 - 50", "50 - 60", "60 - 70","70 - 80", "80 - 90", "90 - 100", ">100") #set plot text
plot_legend <- c("Product A", "Product B")
plot_title <- paste0("Increase % Distribution")
annotate_title <-"Top % Increase"
annotate_prefix_1 <-"Product A = "
annotate_prefix_2 <-"Product B = " df_sum <- df %>%
group_by(product) %>%
summarize(sumFreq=sum(freq))%>%
ungroup()%>%
select(product,sumFreq) df <- merge(df,df_sum,by.x = 'product',by.y='product')
df <- within(df,{rate <- round(freq/sumFreq,digits=)*})
df <- subset(df,select=c(product,rate_cut,rate)) #set order
df$rate_cut <- factor(df$rate_cut,levels=labels_order,ordered = TRUE)
df <- df[order(df$product,df$rate_cut),] #set position
annotate.y <- ceiling(max(round(df$rate,digits = ))/*2.5)
text.offset <- max(round(df$rate,digits = ))/ annotation <- df %>%
mutate(indicator = ifelse(substr(rate_cut,,) %in% c("","","",'>1'),'top','increase' )) %>%
filter(indicator=='top') %>%
dplyr::group_by(product) %>%
dplyr::summarise(total = sum(rate)) %>%
select(product, total) mytheme <- theme_classic() +
theme(
panel.background = element_blank(),
strip.background = element_blank(),
panel.grid = element_blank(),
axis.line = element_line(color = "gray95"),
axis.ticks = element_blank(),
text = element_text(family = "sans"),
axis.title = element_text(color = "gray30", size = ),
axis.text = element_text(size = , color = "gray30"),
plot.title = element_text(size = , hjust = ., color = "gray30"),
strip.text = element_text(color = "gray30", size = ),
axis.line.y = element_line(size=,linetype = 'dotted'),
axis.line.x = element_blank(),
axis.text.x = element_text(vjust = ),
plot.margin = unit(c(0.5,0.5,0.5,0.5), "cm"),
legend.position = c(0.7, 0.9),
legend.text = element_text(color = "gray30")
) ##ggplot
ggplot(df,aes(x=rate_cut, y=rate)) +
geom_bar(stat = "identity", aes(fill = product), position = "dodge", width = 0.5) +
guides(fill = guide_legend(reverse = TRUE)) +
scale_fill_manual(values = c("#00188F","#00BCF2")
,breaks = c("ProductA","ProductB")
,labels = plot_legend
,name = "") +
geom_text(data = df
, aes(label = comma(rate), y = rate +text.offset, color = product)
,position = position_dodge(width =)
, size = ) +
scale_color_manual(values = c("#00BCF2", "#00188F"), guide = FALSE) +
annotate("text", x = , y = annotate.y, hjust = , color = "gray30", label = annotate_title) +
annotate("text", x = 2.5, y = annotate.y, hjust = , color = "gray30", label = paste0(annotate_prefix_1, annotation$total[])) +
annotate("text", x = , y = annotate.y, hjust = , color = "gray30", label = paste0(annotate_prefix_2, annotation$total[])) +
labs(x="Increase Percentage",y="Percent of freq",title=plot_title) +
mytheme +
coord_flip()

参考文档:

ggplot2 barplots : Quick start guide - R software and data visualization

ggplot2 Bar charts

R geom_bar

Labelling Barplot with ggplotAssist(I)

R绘图 第七篇:绘制条形图(ggplot2)的更多相关文章

  1. R绘图 第八篇:绘制饼图(ggplot2)

    geom_bar()函数不仅可以绘制条形图,还能绘制饼图,跟绘制条形图的区别是坐标系不同,绘制饼图使用的坐标系polar,并且设置theta="y": coord_polar(th ...

  2. R绘图 第五篇:绘制散点图(ggplot2)

    ggplot2包中绘制点图的函数有两个:geom_point和 geom_dotplot,当使用geom_dotplot绘图时,point的形状是dot,不能改变点的形状,因此,geom_dotplo ...

  3. R绘图 第六篇:绘制线图(ggplot2)

    线图是由折线构成的图形,线图是把散点从左向右用直线连接起来而构成的图形,在以时间序列为x轴的线图中,可以看到数据增长的趋势. geom_line(mapping = NULL, data = NULL ...

  4. R绘图 第十篇:绘制文本、注释和主题(ggplot2)

    使用ggplot2包绘制时,为了更直观地向用户显示报表的内容和外观,需要使用geom_text()函数添加文本说明,使用annotate()添加注释,并通过theme()来调整非数据的外观. 一,文本 ...

  5. R实战 第七篇:绘图文本表

    文本表是显示数据的重要图形,一个文本表按照区域划分为:列标题,行标题,数据区,美学特征有:前景样式.背景央视.字体.网格线等. 一,使用ggtexttable绘图文本表 载入ggpubr包,可以使用g ...

  6. R绘图 第四篇:绘制箱图(ggplot2)

    箱线图通过绘制观测数据的五数总括,即最小值.下四分位数.中位数.上四分位数以及最大值,描述了变量值的分布情况.箱线图能够显示出离群点(outlier),离群点也叫做异常值,通过箱线图能够很容易识别出数 ...

  7. R绘图 第十一篇:统计转换、位置调整、标度和向导(ggplot2)

    统计转换和位置调整是ggplot2包中的重要概念,统计转换通常使用stat参数来引用,位置调整通常使用position参数来引用. bin是分箱的意思,在统计学中,数据分箱是一种把多个连续值分割成多个 ...

  8. R实战 第七篇:网格(grid)

    grid包是R底层的图形系统,可以绘制几乎所有的图形.除了绘制图形之外,grid包还能对图形进行布局.在绘图时,有时候会遇到这样一种情景,客户想把多个代表不同KPI的图形分布到同一个画布(Page)上 ...

  9. R实战 第五篇:绘图(ggplot2)

    ggplot2包实现了基于语法的.连贯一致的创建图形的系统,由于ggplot2是基于语法创建图形的,这意味着,它由多个小组件构成,通过底层组件可以构造前所未有的图形.ggplot2可以把绘图拆分成多个 ...

随机推荐

  1. vue权威指南笔记01——样式的设置

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  2. mysql中的utf8mb4、utf8mb4_unicode_ci、utf8mb4_general_ci

    1.utf8与utf8mb4(utf8 most bytes 4) MySQL 5.5.3之后增加了utfmb4字符编码 支持BMP(Basic Multilingual Plane,基本多文种平面) ...

  3. java -jar 命令

    java -jar spring.jar 这个命令当你 controller c 之后,程序就自动结束了 java jar spring.jar & &是指在后台运行,但当用户推出(挂 ...

  4. Spring系列(1)--IOC 和 DI

    IOC 和 DI IOC 原理 xml 配置文件配置 bean dom4j 读取配置文件 工厂设计模式 反射机制创建对象 applicationContext.xml 配置文件,该配置文件名可自定义: ...

  5. logstash之input、codec学习

    Logstash最强大的功能在于丰富的过滤器插件.此过滤器提供的并不单单是过滤的功能,还可以对进入过滤器的原始数据进行复杂的逻辑处理.甚至添加独特的事件到后续流程中. 1.logstash基本语法组成 ...

  6. Java设计模式之五 ----- 外观模式和装饰器模式

    前言 在上一篇中我们学习了结构型模式的适配器模式和桥接模式.本篇则来学习下结构型模式的外观模式和装饰器模式. 外观模式 简介 外观模式隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口.这 ...

  7. C#Url处理类

    using System; using System.Text.RegularExpressions; using System.Web; using System.Collections.Speci ...

  8. 转://Linux下tmpfs介绍及使用

    tmpfs介绍 tmpfs是一种虚拟内存文件系统,而不是块设备.是基于内存的文件系统,创建时不需要使用mkfs等初始化它最大的特点就是它的存储空间在VM(virtual memory),VM是由lin ...

  9. 一个非常好的php实现手机号归属地查询接口类

    前一阵子看到了一个非常好的php手机归属地查询的类,写的很精简,查询也很精确!大致代码是这样的: <?php header("Content-type:text/html;charse ...

  10. 转载 WebService 的CXF框架 WS方式Spring开发

    WebService 的CXF框架 WS方式Spring开发   1.建项目,导包. 1 <project xmlns="http://maven.apache.org/POM/4.0 ...