ggplot2包简介

1 ggplot2绘图语法

1.1 案例绘图

  • ggplot函数指定要绘图的数据(通常是数据框),并生成一个空的图形对象(不生成图形)

  • aes(x,y,…)函数用于指定图形属性的映射,其中的x用于指定坐标轴x的变量或数值,y用于指定坐标轴y的变量或数值

  • geom是几何的缩写,表示要绘制的几何对象,在下划线“_”后面指定要绘制的几何图形

  • ggplot2的绘图语法是将各个部分用“+”连接起来

  • 使用theme函数设置图形主题,用于控制或修改图形外观

df <- data2_1 |> gather(R语言,Python语言,key=课程,value=分数)

# 设置图形主题(可根据需要设置,省略时函数会根据默认设置绘图)
mytheme<-theme(plot.title=element_text(size="12"), # 设置主标题字体大小
    axis.title=element_text(size=10),              # 设置坐标轴标签字体大小
    axis.text=element_text(size=9),                # 设置坐标轴刻度字体大小
    legend.position="none")                        # 移除图例

# 绘制图形
p1<-ggplot(data=df,aes(x=性别,fill=性别))+  # 设置x轴,按性别填充颜色
     geom_bar()+                            # 绘制条形图
     ylab("人数")+                          # 设置y轴标签
     mytheme+                       # 使用设置的主题
     ggtitle("(a) 条形图")          # 添加标题

p2<-ggplot(data=df,aes(x=课程,y=分数,fill=性别))+
     geom_boxplot()+                # 绘制箱线图
     facet_wrap(~性别)+             # 按性别分面
     mytheme+ggtitle("(b) 分面箱线图")

p3<-ggplot(data=df,aes(x=分数,fill=课程,alpha=0.2))+ # 设置颜色透明度alpha的值
     geom_density()+                # 绘制核密度图
     xlim(50,105)+                  # 设置x轴值域(数值范围)
     ylim(0,0.07)+                  # 设置y轴值域(数值范围)
     annotate("text",x=68,y=0.015,label="Python语言",size=4)+# 添加注释文本
     annotate("text",x=85,y=0.015,label="R语言",size=4)+
     mytheme+ggtitle("(c) 分组核密度图")

p4<-ggplot(data=data2_1,aes(x=R语言,y=Python语言,fill=性别))+
     geom_point(size=3,shape=21,color="black")+ # 绘制散点图
     facet_wrap(~性别)+              # 按性别分面
     mytheme+ggtitle("(d) 分面散点图")

grid.arrange(p1,p2,p3,p4,ncol=2)       # 按2列组合图形p1、p2、p3、p4

1.2 思考与代码修改

  • aes()函数的fill参数有什么用?aes()函数既可以嵌套在ggplot() 中作全局设定,也可以提取出外通过’+’连接作局部设定。

    在R语言的ggplot2包中,aes()函数用于映射变量到图形属性(如颜色、形状、大小等)。fill参数是aes()中的一个重要参数,主要用于控制图形的填充颜色

  • 修改p1的代码中aes() 提取出ggplot()函数放到geom_bar(),看能不能运行?

  • geom_bar/geom_boxplot/geom_density/geom_point分别代表绘制什么图形?

    柱状图、箱线图、密度图、点图

  • facet_wrap()函数有什么用?在图p2代码中如果注释到这行会有什么后果。

    facet_wrap() 是 ggplot2 中的一个关键函数,用于将数据按某个分类变量拆分成多个子图(分面),并在一个页面中排列展示。

    所有数据会绘制在同一个图中,不同类别的点会重叠在一起。

  • aes(x=分数,fill=课程,alpha=0.2)fill参数代表填充颜色,试将图p3中的fill 参数改为color 看有什么效果?

    • fill 控制填充颜色(密度曲线下方的区域)。

    • alpha = 0.2 设置填充的透明度(浅色半透明)。

    • 不同课程用不同填充色区分,适合面积类图形(如密度图、柱状图)。

  • geom_point(size=3,shape=21,color="black")shape参数代表点的形状,试将图p4中shape参数取值改为25看有什么效果?

    形状变为倒三角

  • 代码grid.arrange(p1,p2,p3,p4,ncol=2)有什么用?相当于graphic包的什么代码?

    这段代码用于将多个ggplot图形(p1p2p3p4)排列在一个画布上,按2列的布局展示(ncol=2),默认自动计算行数(这里是2行)。它是gridExtra包中的函数,专门用于组合和排列图形。

    在R的基础绘图系统(graphics包)中,实现类似功能需要使用 par(mfrow) 或 layout()

# 修改原绘图代码以满足要求

df <- data2_1 |> gather(R语言,Python语言,key=课程,value=分数)

# 设置图形主题(可根据需要设置,省略时函数会根据默认设置绘图)
mytheme<-theme(plot.title=element_text(size="12"), # 设置主标题字体大小
    axis.title=element_text(size=10),              # 设置坐标轴标签字体大小
    axis.text=element_text(size=9),                # 设置坐标轴刻度字体大小
    legend.position="none")                        # 移除图例

# 绘制图形
p1<-ggplot(data=df)+  # 设置x轴,按性别填充颜色
     geom_bar(aes(x=性别,fill=性别))+                            # 绘制条形图
     ylab("人数")+                          # 设置y轴标签
     mytheme+                       # 使用设置的主题
     ggtitle("(a) 条形图")          # 添加标题

p2<-ggplot(data=df,aes(x=课程,y=分数,fill=性别))+
     geom_boxplot()+                # 绘制箱线图
    # facet_wrap(~性别)+             # 按性别分面
     mytheme+ggtitle("(b) 分面箱线图")

p3<-ggplot(data=df,aes(x=分数,color=课程,alpha=0.2))+ # 设置颜色透明度alpha的值
     geom_density()+                # 绘制核密度图
     xlim(50,105)+                  # 设置x轴值域(数值范围)
     ylim(0,0.07)+                  # 设置y轴值域(数值范围)
     annotate("text",x=68,y=0.015,label="Python语言",size=4)+# 添加注释文本
     annotate("text",x=85,y=0.015,label="R语言",size=4)+
     mytheme+ggtitle("(c) 分组核密度图")

p4<-ggplot(data=data2_1,aes(x=R语言,y=Python语言,fill=性别))+
     geom_point(size=3,shape=25,color="black")+ # 绘制散点图
     facet_wrap(~性别)+              # 按性别分面
     mytheme+ggtitle("(d) 分面散点图")

grid.arrange(p1,p2,p3,p4,ncol=2)       # 按2列组合图形p1、p2、p3、p4

2 图形外观——设置坐标轴

2.1 案例绘图

  • 图(a)是默认绘制的类别轴(本图为x轴)顺序是R语言、Python语言,使用scale_x_discrete(limits=c())可根据需改变类别顺序

  • 图(b)是设置coord_flip()使坐标轴互换,同时,将x轴(类别轴)标签旋转90度

  • 图(c)使用theme(axis.title.x=element_blank())移除y轴标签,要移除x轴标签使用类似的设置;设置theme(axis.ticks.y=element_blank())移除y轴的刻度线

  • 图(d)使用theme(axis.ticks=element_blank())移除所有的刻度线,将坐标轴标签旋转是为了改变标签的角度。

  • 当标签较多时,也可以设置scale_x_discrete(guide=guide_axis(n.dodge=2))使x轴标签排成为2行。使用xlim()可以数值x轴的数值范围。设置x轴数值范围时,函数会在该范围内设置坐标轴刻度,重新设置刻度线可以使用scale_x_continuous(limits=c(),breaks=c())

# 设置图形主题(可根据需要设置)
mytheme<-theme(plot.title=element_text(size="11"), # 设置主标题字体大小
   axis.title=element_text(size=10),               # 设置坐标轴标签字体大小
   axis.text=element_text(size=9),                 # 设置坐标轴刻度字体大小
   legend.position="none")                         # 移除图例

# 图(a)修改类别轴项目顺序
p1<-ggplot(data=df,aes(x=课程,y=分数,fill=课程))+
    geom_boxplot()+                                      # 绘制箱线图
    scale_x_discrete(limits=c("Python语言","R语言"))+    # 修改类别轴项目顺序
    mytheme+ggtitle("(a) 修改类别轴项目顺序\n默认顺序R语言、Python语言")

# 图(b)坐标轴互换,并反转x轴元素的顺序
p2<-ggplot(data=df,aes(x=课程,y=分数,fill=课程))+
    geom_boxplot()+
    coord_flip()+                                        # 坐标轴互换(或者设置y=分数,x=课程)
    ylim(54,101)+                                        # 设置y轴值域(数值范围)
    theme(axis.text.y=element_text(size=9,angle=90,hjust=0.5,vjust=0.5))+   # 设置y轴标角度,并进行水平和垂直位置调整
    scale_x_discrete(limits=rev(levels(df$课程)))+# 反转类别轴项目顺序
    mytheme+ggtitle("(b) 坐标轴互换\n反转x轴元素的顺序并旋转90度")

# 图(c)移除y轴刻度线和标签,删除x轴和y轴次网格线
p3<-ggplot(data=df,aes(x=分数,fill=课程,alpha=0.2))+
    geom_density()+                                         # 绘制核密度图
    xlim(50,105)+                                           # 设置x轴值域(数值范围)
    ylim(0,0.07)+                                           # 设置y轴值域(数值范围)
    theme(axis.title.y=element_blank(),                     # 移除y轴标签
          axis.ticks.y=element_blank(),                     # 移除y轴刻度线
          panel.grid.minor.x=element_blank(),               # 去掉x轴次网格线
          panel.grid.minor.y=element_blank())+              # 去掉y轴次网格线
    annotate("text",x=69,y=0.015,label="Python语言",size=3)+# 添加注释文本
    annotate("text",x=85,y=0.015,label="R语言",size=3)+
    mytheme+ggtitle("(c) 移除y轴刻度线和y轴标签\n去掉x轴和y轴次网格线")

# 图(d)移除所有刻度线,刻度标签旋转90度
p4<-ggplot(data=df,aes(x=分数,fill=课程,alpha=0.2))+
    geom_density()+                                       # 绘制核密度图
    scale_x_continuous(limits=c(50,100),
     breaks=c(50,55,60,65,70,75,80,85,90,95,100))+        # 设置x轴值域和刻度线位置
    scale_y_continuous(limits=c(0,0.07),
     breaks=c(0,0.01,0.02,0.03,0.04,0.05,0.06,0.07))+     # 设置y轴值域和刻度线位置
    ylab("密度")+                                         # 设置y轴标签
    theme(axis.ticks=element_blank(),                     # 移除所有刻度线
     axis.line=element_line(color="blue",linewidth=1.5),  # 添加坐标轴直线
     axis.text.x=element_text(size=9,angle=90,hjust=1,vjust=1))+      # 设置x轴标签角度
    annotate("text",x=69,y=0.015,label="Python语言",size=3)+          # 添加注释文本
    annotate("text",x=85,y=0.015,label="R语言",size=3)+
mytheme+ggtitle("(d) 移除所有刻度线\nx轴刻度标签旋转90度")

grid.arrange(p1,p2,p3,p4,ncol=2)       # 组合图形

2.2 思考与代码修改

  • ggplot2 包通过theme() 函数设置主题要素参数,如何实现全局设定和局部设定?

    全局主题设定会应用到当前R会话中的所有ggplot2图形上,使用theme_set()函数实现

    局部主题设定只影响单个图形,通过在具体图形对象上使用theme()函数实现

    在 ggplot2 中,theme() 函数用于自定义图形的非数据元素(如标题、字体、背景、图例等)。你可以通过全局设定局部设定两种方式应用主题参数

  • scale_x_discrete()函数有什么作用?如何将p1的横轴标题由“课程”改为“科目”。

    修改轴标签(labels)调整类别顺序(limits) 处理缺失类别(drop)位置调整(position)自定义美学映射

  • 将图p2注释掉theme(axis.text.y=element_text(size=9,angle=90,hjust=0.5,vjust=0.5))有什么影响?

    • 文本大小:不再强制设为size=9,会继承全局主题设置或默认值(通常size=11

    • 文本角度:不再旋转90度(angle=90),恢复为默认的水平显示(angle=0

    • 对齐方式:不再使用hjust=0.5vjust=0.5的居中调整,恢复默认对齐方式

  • annotate() 函数除了能在图中添加文本注释还能添加什么?将p3中“R语言”的文本注释放在蓝色区域的右边。

    annotate() 函数在 ggplot2 中是一个多功能注释工具,除了添加文本外,还能添加多种图形元素。

  • 将p4的x轴刻度标签角度改为45度

# 修改原绘图代码以满足要求

# 设置图形主题(可根据需要设置)
mytheme<-theme(plot.title=element_text(size="11"), # 设置主标题字体大小
   axis.title=element_text(size=10),               # 设置坐标轴标签字体大小
   axis.text=element_text(size=9),                 # 设置坐标轴刻度字体大小
   legend.position="none")                         # 移除图例

# 图(a)修改类别轴项目顺序
p1<-ggplot(data=df,aes(x=课程,y=分数,fill=课程))+
    geom_boxplot()+                                      # 绘制箱线图
    scale_x_discrete(limits=c("Python语言","R语言"),name = "科目")+    # 修改类别轴项目顺序
    mytheme+ggtitle("(a) 修改类别轴项目顺序\n默认顺序R语言、Python语言")

# 图(b)坐标轴互换,并反转x轴元素的顺序
p2<-ggplot(data=df,aes(x=课程,y=分数,fill=课程))+
    geom_boxplot()+
    coord_flip()+                                        # 坐标轴互换(或者设置y=分数,x=课程)
    ylim(54,101)+                                        # 设置y轴值域(数值范围)
   # theme(axis.text.y=element_text(size=9,angle=90,hjust=0.5,vjust=0.5))+   # 设置y轴标角度,并进行水平和垂直位置调整
    scale_x_discrete(limits=rev(levels(df$课程)))+# 反转类别轴项目顺序
    mytheme+ggtitle("(b) 坐标轴互换\n反转x轴元素的顺序并旋转90度")

# 图(c)移除y轴刻度线和标签,删除x轴和y轴次网格线
p3<-ggplot(data=df,aes(x=分数,fill=课程,alpha=0.2))+
    geom_density()+                                         # 绘制核密度图
    xlim(50,105)+                                           # 设置x轴值域(数值范围)
    ylim(0,0.07)+                                           # 设置y轴值域(数值范围)
    theme(axis.title.y=element_blank(),                     # 移除y轴标签
          axis.ticks.y=element_blank(),                     # 移除y轴刻度线
          panel.grid.minor.x=element_blank(),               # 去掉x轴次网格线
          panel.grid.minor.y=element_blank())+              # 去掉y轴次网格线
    annotate("text",x=69,y=0.015,label="Python语言",size=3)+# 添加注释文本
    annotate("text",x=100,y=0.015,label="R语言",size=3)+
    mytheme+ggtitle("(c) 移除y轴刻度线和y轴标签\n去掉x轴和y轴次网格线")

# 图(d)移除所有刻度线,刻度标签旋转90度
p4<-ggplot(data=df,aes(x=分数,fill=课程,alpha=0.2))+
    geom_density()+                                       # 绘制核密度图
    scale_x_continuous(limits=c(50,100),
     breaks=c(50,55,60,65,70,75,80,85,90,95,100))+        # 设置x轴值域和刻度线位置
    scale_y_continuous(limits=c(0,0.07),
     breaks=c(0,0.01,0.02,0.03,0.04,0.05,0.06,0.07))+     # 设置y轴值域和刻度线位置
    ylab("密度")+                                         # 设置y轴标签
    theme(axis.ticks=element_blank(),                     # 移除所有刻度线
     axis.line=element_line(color="blue",linewidth=1.5),  # 添加坐标轴直线
     axis.text.x=element_text(size=9,angle=90,hjust=1,vjust=1))+      # 设置x轴标签角度
    annotate("text",x=69,y=0.015,label="Python语言",size=3)+          # 添加注释文本
    annotate("text",x=85,y=0.015,label="R语言",size=3)+
mytheme+ggtitle("(d) 移除所有刻度线\nx轴刻度标签旋转90度")

grid.arrange(p1,p2,p3,p4,ncol=2)       # 组合图形

3 图形外观——设置图形标题

3.1 案例绘图

# 初始图形,所有设置均为默认
p<-ggplot(data=df)+aes(x=课程,y=分数,fill=性别)+
    geom_boxplot()    # 绘制箱线图

# 设置标题
p1<-p+ggtitle("(a) 这里是标题(默认设置)")   # 添加标题

p2<-p+ggtitle("(b) 这里是标题(设置字体大小,粗体字)")+
theme(plot.title=element_text(size=10,face="bold"))# 设置标题字体大小

p3<-p+labs(title=("(c) 这里是标题(标题位置居中)\n(标题换行)"))+  # 标题换行(在\n处断行)
theme(plot.title=element_text(size=12,hjust=0.5))   # 调整标题位置(居中)

p4<-p+ggtitle("(d) 这里是主标题(蓝色粗斜体)","(这里是副标题)")+ # 添加副标题
theme(plot.title=element_text(size=12,face="bold.italic",color="blue3"))  # 设置标题为粗斜体字,蓝色

gridExtra::grid.arrange(p1,p2,p3,p4,ncol=2)       # 组合图形

3.2 思考

  • ggtitle() 中第一个参数为主标题,第二个参数为副标题;再通过主题函数theme(plot.title=element_text()) 设置标题的具体属性

  • element_text() 为文本属性设定函数,一共有多少个参数可以设定?

    在 ggplot2 的 element_text() 函数中,官方文档明确列出的可配置参数共有 12 个,用于控制文本的字体、颜色、对齐、边距等属性。

  • element_text(size=10,face="bold") 代表什么意思?

    上述代码会将图表的 标题 显示为 10磅加粗 的文字,而坐标轴标签(如“mpg”“wt”)会显示为 8磅斜体

  • element_text() 的设定会覆盖主题(theme_*())中的默认样式。

  • element_text(size=12,hjust=0.5)代表什么意思?

    element_text(size = 12, hjust = 0.5) 是一个用于设置文本样式的函数调用,主要控制文本的 大小 和 水平对齐方式size = 12设置文本的字体大小为 12 磅(单位是 pt),适用于标题、轴标签、图例文字等。例如:将图表标题的字体放大到 12 磅。hjust = 0.5控制文本的 水平对齐方式0.5 表示 居中对齐

  • element_text(size=12,face="bold.italic",color="blue3") 代表什么意思?

    element_text(size = 12, face = "bold.italic", color = "blue3") 是一个用于自定义文本样式的函数调用。size = 12设置文本的字体大小为 12 磅pt),适用于标题、轴标签、图例文字等。face = "bold.italic"

    • 设置文本字体样式为 加粗且斜体。其他可选值:

    • color = "blue3"

    • 设置文本颜色为 深蓝色"blue3" 是 R 中的预定义颜色名称,类似十六进制值 #0000CD)。

    • 也可使用十六进制值(如 "#FF0000")或 RGB 名称(如 "royalblue")。

4 图形外观——设置图例

4.1 案例绘图

# 初始图形,所有设置均为默认
p<-ggplot(data=df)+aes(x=课程,y=分数,fill=性别)+
  geom_boxplot() # 绘制箱线图

# 设置图例
p1<-p+ggtitle("(a) 默认图例")
p2<-p+ggtitle("(b) 移除图例")+
    theme(legend.position="none")              # 移除图例(或设置guides(fill="none"))
p3<-p+ggtitle("(c) 设置图例位置、字体、背景和边框颜色")+
    theme(legend.text=element_text(size=8,color="blue"), # 设置图例字体大小和颜色
          legend.position="top",               # 设置图例位置(顶部)
          legend.background=element_rect(fill="grey85",color="grey"),
                                               # 设置图例背景色和边框颜色
          legend.key=element_rect(color="blue",linewidth=0.25))
                                               # 设置图例键的颜色和线宽

p4<-p+ggtitle("(d) 设置图例位置、摆放方式和顺序")+
    theme(legend.position=c(0.75,0.9),         # 设置图例位置
          legend.background=element_blank(),  # 移除图例整体边框
          legend.text=element_text(size=8))+  # 设置图例字体大小
    guides(fill=guide_legend(nrow=1,title=NULL))+
                                   # 设置图例摆放方式(1行,去掉图例标题)
    scale_fill_discrete(limits=c("女","男"))   # 修改图例顺序
Warning: A numeric `legend.position` argument in `theme()` was deprecated in ggplot2
3.5.0.
ℹ Please use the `legend.position.inside` argument of `theme()` instead.
gridExtra::grid.arrange(p1,p2,p3,p4,ncol=2)    # 组合图形

4.2 思考与代码修改

  • theme() 函数中legend.text/legend.position/legend.background/legend.key 四个参数分别设定什么方面的内容?

    legend.text作用:控制图例中文字标签的样式

    legend.position作用:控制图例在图形中的位置

    legend.background作用:设置图例区域的背景样式

    legend.key作用:控制图例中颜色/符号键(即色块或形状)的样式

  • element_rect() 矩形对象属性设定函数,legend.background/legend.key 两个参数为什么需要用它设定?

    在ggplot2中,element_rect() 是专门用于定义 矩形元素样式 的核心函数,legend.background 和 legend.key 这两个参数之所以需要通过它来设定,是由它们的 物理属性和功能需求 决定的。

  • 修改图p3的代码,将图例位置改为图形下方,将图例标题legend.title”性别“的字体颜色也改为蓝色。

  • 修改图p4的代码,将图例位置改为图中的右下方,图例中男左女右。

# 修改原绘图代码以满足要求

p3<-p+ggtitle("(c) 设置图例位置、字体、背景和边框颜色")+
    theme(legend.text=element_text(size=8,color="blue"), # 设置图例字体大小和颜色
          legend.position="bottom",               # 设置图例位置(顶部)
          theme(plot.title=element_text(size=8,color="blue")),
          legend.background=element_rect(fill="grey85",color="grey"),
                                               # 设置图例背景色和边框颜色
          legend.key=element_rect(color="blue",linewidth=0.25))
                                               # 设置图例键的颜色和线宽

p4<-p+ggtitle("(d) 设置图例位置、摆放方式和顺序")+
    theme(legend.position=c(0.75,0.9),         # 设置图例位置
          legend.background=element_blank(),  # 移除图例整体边框
          legend.text=element_text(size=8))+  # 设置图例字体大小
    guides(fill=guide_legend(nrow=1,title=NULL))+
                                   # 设置图例摆放方式(1行,去掉图例标题)
    scale_fill_discrete(limits=c("男","女"))   # 修改图例顺序

gridExtra::grid.arrange(p1,p2,p3,p4,ncol=2)    # 组合图形

5 图形外观——长标签处理

5.1 案例绘图

df<-data.frame(
  专业=c("流行病和卫生统计","数据科学与大数据技术","数理统计"),
  课程=c("Python机器学习原理与实践","数据建模","数据科学统计基础"),
  平均分数=c(76,88,82))

# 绘制条形图
p<-ggplot(df)+aes(x=课程,y=平均分数,fill=专业)+
  geom_col(width=0.8,color="grey50")

# 图(a)默认绘制
p1<-p+theme(panel.background=element_rect(fill="lightyellow"),# 设置图形面板背景色
            plot.background=element_rect(fill="lightblue"))+# 设置图形整体背景色
ggtitle("(a) 默认绘制")

# 图(b)在适当位置折行
p2<-p+scale_x_discrete(labels=c("Python\n机器学习\n原理与实践","数据建模","数据科学\n统计基础"))+                    # 将x轴的长标签折行
  theme(axis.text=element_text(lineheight=1))+ # 设置x轴标签文本的高度
  scale_fill_discrete(labels=c("流行病和\n卫生统计","数据科学\n与大数据\n技术","数理统计"))+                              # 将图例标签折行
theme(legend.text=element_text(lineheight=1),
      legend.key.height=unit(1,"cm"))+            # 设置图例文本和色键高度
  ggtitle("(b) 在适当位置折行")

# 图(c)设置标签文本宽度
p3<-p+scale_x_discrete(labels=function(x) str_wrap(x,width=8))+  # 设置x轴标签宽度
  theme(axis.text=element_text(lineheight=1))+                   # 设置x轴标签文本的高度
  scale_fill_discrete(labels=function(x) str_wrap(x,width=8))+   # 设置图例标签宽度
  theme(legend.text=element_text(lineheight=1),
        legend.key.height=unit(1,"cm"))+
  ggtitle("(c) 设置标签文本宽度")

grid.arrange(p1,p2,p3,layout_matrix=rbind(c(1,1),c(2,3))) 

5.2 思考

  • R语言的”\“为转义符,"Python\n机器学习\n原理与实践" 中的\n表示什么意思?

    换行

  • grid.arrange()函数中参数设定layout_matrix=rbind(c(1,1),c(2,3)) 表示什么意思?

    grid.arrange() 中的 layout_matrix = rbind(c(1,1), c(2,3)) 表示将图形排列成一个 2行×2列的布局,具体含义如下:

    1. 第一行c(1,1)

      • 图形1(编号1跨两列,独占整行。
    2. 第二行c(2,3)

      • 左侧放置图形2(编号2),右侧放置图形3(编号3),两者平分宽度
  • 在 grid.arrange() 函数(来自 gridExtra 包)中,layout_matrix 参数通过矩阵形式 精确控制多图形的排列布局

6 图形外观——使用已有图形主题

6.1 案例代码

df <- data2_1 |> gather(R语言,Python语言,key=课程,value=分数)

p<-ggplot(data=df)+aes(x=课程,y=分数,fill=性别)+
    geom_boxplot()    # 绘制箱线图

p1<-p+theme_grey()+ggtitle("(a)+theme_grey")         # 默认主题
p2<-p+theme_bw()+ggtitle("(b) theme_bw")             # 黑白主题
p3<-p+theme_minimal()+ggtitle("(c) theme_minimal")   # 最小主题
p4<-p+theme_classic()+ggtitle("(d) theme_classic")   # 经典主题


gridExtra::grid.arrange(p1,p2,p3,p4,ncol=2)       # 组合图形

除了ggplot2包自带的主题函数外,还有很多包提供主题函数。

library(ggthemes)
Warning: package 'ggthemes' was built under R version 4.3.3
p1<-p+theme_economist_white()+ggtitle("(a) theme_economist_white")  # 《经济学人》杂志白色主题
p2<-p+theme_excel()+ggtitle("(b) theme_excel")   # Excel主题
p3<-p+theme_few()+ggtitle("(c) theme_few")       # 少数人使用的图形主题
p4<-p+theme_stata()+ggtitle("(d) theme_stata")   # 基于Stata图形方案的主题

gridExtra::grid.arrange(p1,p2,p3,p4,ncol=2)      # 组合图形

6.2 思考与代码修改

  • 试在Deepseek中提问”R语言中针对ggpolt函数绘图,有哪些主题包和主题函数?“

  • ggthemes/hrbrthemes/ggpubr等包提供多种商业化绘图主题。选择四种你喜欢的主题设置,应用于案例绘图中。

library(ggthemes)
library(hrbrthemes)
Warning: package 'hrbrthemes' was built under R version 4.3.3
library(ggpubr)
Warning: package 'ggpubr' was built under R version 4.3.3
# 安装必要包(如果尚未安装)
if (!requireNamespace("ggplot2", quietly = TRUE)) install.packages("ggplot2")
if (!requireNamespace("ggthemes", quietly = TRUE)) install.packages("ggthemes")
if (!requireNamespace("hrbrthemes", quietly = TRUE)) install.packages("hrbrthemes")
if (!requireNamespace("ggpubr", quietly = TRUE)) install.packages("ggpubr")

# 加载包
library(ggplot2)
library(ggthemes)
library(hrbrthemes)
library(ggpubr)

# 创建基础图形(使用mtcars数据集)
base_plot <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
  geom_point(size = 3, alpha = 0.8) +
  geom_smooth(method = "lm", se = FALSE) +
  labs(title = "汽车重量与燃油效率关系",
       subtitle = "按气缸数分组",
       x = "重量 (千磅)",
       y = "每加仑里程 (MPG)",
       color = "气缸数",
       caption = "数据来源: 1974 Motor Trend US杂志") +
  theme(plot.title = element_text(face = "bold"),
        legend.position = "bottom")

# 1. ggthemes中的经济学人主题
plot_economist <- base_plot +
  theme_economist() +
  scale_color_economist() +
  labs(title = "经济学人主题 (ggthemes)",
       subtitle = "专业商业出版物风格")

# 2. hrbrthemes中的现代主题
plot_ipsum <- base_plot +
  theme_ipsum() +
  scale_color_ipsum() +
  labs(title = "IPSUM现代主题 (hrbrthemes)",
       subtitle = "干净、专业的现代风格") +
  theme(axis.title.x = element_text(hjust = 0.5),
        axis.title.y = element_text(hjust = 0.5))

# 3. ggpubr中的科学出版物主题(使用默认颜色标度)
plot_pubr <- base_plot +
  theme_pubclean() +  # 使用pubclean主题代替
  scale_color_viridis_d() +  # 使用viridis色标代替
  labs(title = "科学出版物主题 (ggpubr)",
       subtitle = "适合学术出版物的简洁风格")

# 4. ggthemes中的华尔街日报主题
plot_wsj <- base_plot +
  theme_wsj() +
  scale_color_wsj() +
  labs(title = "华尔街日报主题 (ggthemes)",
       subtitle = "经典商业新闻风格") +
  theme(plot.title = element_text(size = 12),
        plot.subtitle = element_text(size = 10))

# 使用ggpubr的ggarrange函数将四个图形排列在一起
final_plot <- ggarrange(plot_economist, plot_ipsum, 
                        plot_pubr, plot_wsj,
                        ncol = 2, nrow = 2,
                        common.legend = TRUE,
                        legend = "bottom")
`geom_smooth()` using formula = 'y ~ x'
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <e6>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <b0>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <94>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <e7>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <bc>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <b8>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <e6>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <95>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <b0>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <e6>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <b0>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <94>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <e7>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <bc>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <b8>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <e6>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <95>
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
conversion failure on '气缸数' in 'mbcsToSbcs': dot substituted for <b0>
`geom_smooth()` using formula = 'y ~ x'
`geom_smooth()` using formula = 'y ~ x'
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family 'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
'Arial Narrow' not found in PostScript font database
`geom_smooth()` using formula = 'y ~ x'
`geom_smooth()` using formula = 'y ~ x'
# 显示图形并添加整体标题
annotate_figure(final_plot,
                top = text_grob("ggplot2商业化主题展示", 
                               color = "black", face = "bold", size = 16))
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family not found in Windows font database
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family not found in Windows font database
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family not found in Windows font database
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family not found in Windows font database
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family not found in Windows font database
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family not found in Windows font database

7 添加注释

7.1 案例绘图

d <- data2_1
p<-ggplot(data=d)+aes(x=R语言,y=Python语言)+
    geom_point(size=3,shape=21,color="black",fill="red2")+ # 绘制点
    scale_x_continuous(breaks=c(70,75,80,85,90,95))+   # 设置x轴值域和刻度线位置
    geom_smooth(method = lm)          # 添加线性回归线和置信带

# 添加注释
p+geom_vline(xintercept=mean(d$R语言),linetype="twodash",color="grey50",size=0.5)+  # 添加x的均值线(垂直线)
  geom_hline(yintercept=mean(d$Python语言),linetype="twodash",color="grey50",size=0.5)+ # 添加y的均值线(水平线)
  geom_point(x=mean(d$R语言),y=mean(d$Python语言),shape=21,size=5,fill="yellow")+# 添加均值点
  annotate("text",x=72,y=81,label="相关系数: r = ",size=5,color="red3")+  # 添加注释文本
  annotate("text",x=77.2,y=81,label=round(cor(d$R语言,d$Python语言),4),size=5,color="red3")+  # 添加相关系数
  geom_rect(xmin=87, xmax=97, ymin=56.5,ymax=63,fill="grey85")+# 添加矩形
  annotate("text",x=92,y=60,parse=TRUE,size=5,color="red3",label="r==frac(cor(xy),sqrt(var(x)*var(y)))")+  # 添加相关系数的数学表达式
  annotate("text",x=84,y=81,label="回归线:",size=5,color="blue3")+  # 添加注释文本
  annotate("text",x=88.8,y=81.3,parse=TRUE,size=4.5,color="blue3",label="hat(y)==hat(beta)[0]+hat(beta)[1]*x")+  # 添加回归方程数学表达式
  annotate("segment",x=68.5,xend=79,y=79.8,yend=79.8,color="red4",size=0.5)+ # 添加直线
  annotate("segment",x=88,xend=92,y=80,yend=78,color="blue",size=1,arrow=arrow(angle=15,length=unit(0.2,"inches")))  # 添加带箭头的线
Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.
`geom_smooth()` using formula = 'y ~ x'

7.2 思考

  • annotate()函数中参数parse=TRUE 有什么用,尝试将其删除观测结果变化。

    在 ggplot2 的 annotate() 函数中,parse = TRUE 参数的作用是 允许在文本注释中使用数学表达式或符号(通过R的表达式语法实现)。启用后,文本字符串会被解析为R的数学表达式,从而支持显示公式、上下标、希腊字母等科学排版内容。

  • 如何将相关性公式的背景框颜色去掉?

    在ggplot2中,若要去除相关性公式(或其他文本注释)的背景框颜色,可以通过调整 annotate() 或 geom_text() 的图形属性实现。

8 图形分面

案例绘图

df <- data2_1 |> gather(R语言,Python语言,key=课程,value=分数)

p1<-ggplot(data=df)+aes(x=课程,y=分数,fill=性别)+geom_boxplot()+
    facet_wrap(~性别,ncol=2)+              # 按性别2列分面
    ggtitle("(a) 按性别2列分面")

p2<-ggplot(data=df)+aes(x=课程,y=分数,fill=专业)+geom_boxplot()+
    facet_grid(性别~.)+                   # 按性别2行分面
    ggtitle("(b) 按性别2行分面")

p3<-ggplot(data=df)+aes(x=课程,y=分数,fill=性别)+geom_boxplot()+
    facet_wrap(~专业,ncol=3) +             # 按专业3列分面
    ggtitle("(c) 按专业3列分面")

p4<-ggplot(data=df)+aes(x=专业,y=分数,fill=专业)+geom_boxplot()+
    facet_grid(课程~性别)+              # 按课程(行)和性别(列)分面
    theme(panel.spacing.x=unit(0.2,"lines"),   # 设置子图的x轴间距
          panel.spacing.y=unit(0.1,"lines"),   # 设置子图的y轴间距
          strip.text=element_text(size=10),    # 设置分面字体大小
          strip.background=element_rect(fill="skyblue",color="blue4"))+
                                        # 设置分面背景颜色和边框颜色
    ggtitle("(d) 按课程(行)和性别(列)分面")

gridExtra::grid.arrange(p1,p2,p3,p4,ncol=2)       # 组合图形

8.1 思考

  • 分面函数facet_grid()如何使用?

    facet_grid() 是 ggplot2 中用于 按变量分行/列排列多子图 的核心分面函数,适用于基于分类变量的系统化对比。

  • 在主题函数theme() 中,以什么开头的参数控制绘图分面要素的属性?

    在 ggplot2 的 theme() 函数中,所有控制 分面(facet)要素属性 的参数均以 strip. 开头,用于调整分面标签的外观和布局。

9 图形组合

9.1 案例绘图

# 设置图形主题(可根据需要设置)
mytheme<-theme(plot.title=element_text(size="11"), # 设置主标题字体大小
   axis.title=element_text(size=10),               # 设置坐标轴标签字体大小
   axis.text=element_text(size=9),                 # 设置坐标轴刻度字体大小
   legend.position="none")

p1<-ggplot(data=df)+aes(x=性别,fill=性别)+
     geom_bar(width=0.8)+ylab("人数")+           # 绘制条形图
     mytheme+ggtitle("(a) 条形图")

p2<-ggplot(data=df)+aes(x=分数)+
geom_histogram(binwidth=5,fill="lightgreen",color="gray50")+# 绘制直方图
     mytheme+ggtitle("(b) 直方图")

p3<-ggplot(data=df)+aes(x=专业,y=分数,fill=专业)+
     geom_boxplot()+                # 绘制箱线图
     mytheme+ggtitle("(c) 箱线图")

p4<-ggplot(data=df,aes(x=课程,y=分数,fill=课程))+
     geom_violin()+                 # 绘制小提琴图
     mytheme+ggtitle("(d) 小提琴图")

p5<-ggplot(data=df)+aes(x=分数,fill=课程,alpha=0.2)+
    geom_density()+                # 绘制核密度图
    xlim(50,105)+ylim(0,0.07)+
    mytheme+ggtitle("(e) 核密度图")

9.2 页面布局1

# 按行填充子图,行高比为1:2
grid.arrange(p1,p2,p3,p5,            # 组合图形p1、p2、p3、p5
    heights=c(1,2),                  # 设置行高为1:2
    layout_matrix=rbind(c(1,2,3),c(5,5,5))) # 2行3列的矩阵布局

9.3 页面布局2

# 按行填充子图,行高比为1:2:1
grid.arrange(p1,p2,p3,p4,p5,            # 组合图形p1、p2、p3、p4、p5
    heights=c(1,2,1),                   # 设置行高为1:2:1
    layout_matrix=rbind(c(1,2,2),c(5,5,5),c(3,3,4))) # 3行3列矩阵布局

9.4 页面布局3

# 按列填充子图,列宽比为1:2
grid.arrange(p1,p2,p3,p4,p5,                # 组合图形p1、p2、p3、p4、p5
    widths=c(1,2),                          # 设置列宽为1:2
    layout_matrix=cbind(c(1,4,3),c(2,5,5))) #  3行2列矩阵布局