R语言 如何自定义ggplot2中的facet plot的边界
在这篇文章中,我们将讨论如何在R编程语言的ggplot2中自定义面图的边框。
分面图,是指根据一个分类变量对数据进行细分,并以相同的比例绘制一系列类似的图。Facetting帮助我们显示两类以上的数据之间的关系。当我们有多个变量时,通过分面可以将其在一个图中绘制成更小的图。
我们可以使用ggplot2包中的facet_wrap()函数轻松地绘制一个分面图。当我们在ggplot2中使用facet_wrap()时,默认情况下它会在灰色框中给出一个标题。
语法: plot + facet_wrap( ~facet-variable)
其中 。
- facet-variable: 决定了要围绕哪个变量来划分绘图。
创建一个基本的分面图
这里是一个基本的分面图,它使用了R语言原生提供的钻石数据框架。我们使用了facet_wrap()函数和~cut函数,将图表根据其清晰度划分成不同的面。
# load library tidyverse
library(tidyverse)
# set theme_bw()
theme_set(theme_bw(18))
# Basic facet plot divided according to category
# clarity diamonds data frame is used in plot which
# is provided natively by R Language
# ggplot() function is used to plot the chart
ggplot(diamonds, aes(x="price")) +
# geom_bar function is used to create bar plot
geom_bar()+
# facet_wrap() function divides the plot in
# facets according to category of clarity
facet_wrap(~clarity)
输出 。
移除切面图中面板之间的空间
为了去除面板之间的空间,我们使用theme()函数的panel.spacing.x / panel.spacing.y参数。我们甚至可以用这个方法手动指定面板之间需要的空间量。
语法: plot + theme( panel.spacing.x / panel.spacing.y )
例子 。
这里,我们使用钻石数据集创建了一个切面条形图,并通过使用theme()函数的panel.spacing.x和panel.spacing.y参数去除面板间的空间。
# load library tidyverse
library(tidyverse)
# set theme_bw()
theme_set(theme_bw(18))
# Basic facet plot divided according to category clarity
# diamonds data frame is used in plot which
# is provided natively by R Language
# ggplot() function is used to plot the chart
ggplot(diamonds, aes(x="price")) +
# geom_bar function is used to create bar plot
geom_bar()+
# facet_wrap() function divides the plot in
# facets according to category of clarity
facet_wrap(~clarity)+
# theme function with panel.spacing argument
# is used to modify space between panels
theme( panel.spacing.x = unit(0,"line"),
panel.spacing.y = unit(0,"line"))
输出 。
移除面图中的面板边框线
为了去除面板边线,我们使用theme()函数的panel.border参数。我们使用element.blank()函数作为panel.border参数的参数来去除边线。
语法: plot + theme( panel.border = element_blank() )
例子 。
在这里,我们使用钻石数据集创建了一个切面条形图,并通过在theme()函数中使用panel.border aselement_blank()删除了面板边框。
# load library tidyverse
library(tidyverse)
# set theme_bw()
theme_set(theme_bw(18))
# Basic facet plot divided according to category clarity
# diamonds data frame is used in plot which
# is provided natively by R Language
# ggplot() function is used to plot the chart
ggplot(diamonds, aes(x="price")) +
# geom_bar function is used to create bar plot
geom_bar()+
# facet_wrap() function divides the plot in
# facets according to category of clarity
facet_wrap(~clarity)+
# theme function with panel.border is
# used to remove border of facet panels
theme( panel.border = element_blank() )
输出 。