如何在 R 中使用 ggplot2 增加分面图之间的间距?
在本文中,我们将看到如何在 R 编程语言中使用 ggplot2 增加分面图之间的间距。
注意:这里使用了线图,对于任何其他图也可以这样做。
要创建 R 图,我们将使用ggplot()函数并制作折线图,并为其添加geom_line()函数。最后,对于面网格,我们将使用facet_grid()函数。
Syntax : facet_grid(facets)
Parameter :
- facets : Generally facet_grid have many parameters but facets are necessary to specify in which we assign rows and columns where we want grid. As in above syntax, we use Labels vector for rows and nothing for columns. When we have Nothing to specify then we use ‘.’ as here we use facet_grid(Labels ~ .) .
Return : Layout panels in a grid.
让我们首先绘制初始图形,以便差异明显。
例子:
R
# Load Package
library("ggplot2")
# Create a DataFrame
DF <- data.frame(X = rnorm(200),
Y = rnorm(200),
Labels = c("Label 1", "Label 2",
"Label 3", "Label 4"))
# Create a lineplot using ggplot2
# with Facet Grids.
ggplot(DF, aes(X, Y)) +
geom_line(color = "dark green") +
facet_grid(Labels ~ .)
R
# Load Package
library("ggplot2")
# Create a DataFrame
DF <- data.frame(X = rnorm(200),
Y = rnorm(200),
Labels = c("Label 1", "Label 2",
"Label 3", "Label 4"))
# Create a lineplot using ggplot2 with
# 2 cm space between Facet Panels.
ggplot(DF, aes(X, Y)) +
geom_line(color = "dark green") +
facet_grid(Labels ~ .) +
theme(panel.spacing = unit(2, "cm", data = NULL))
输出:
正如您在上图中看到的,刻面网格之间有一些空间,默认情况下约为0.2 厘米。要增加它,请将theme()函数添加到 facet_grid函数。在 theme() 内部将所需的值传递给 panel.spacing 参数。
Syntax : theme(panel.spacing)
Parameter :
- panel.spacing : Generally, theme() has many parameters to specify the theme of plot. we can use them as per our requirements but for change the space between Facets, we will use only panel.spacing parameter. which is used to specify spacing between facet panels. Here we use unit() function as a value of panel.spacing parameter for unit object.
Return : Theme of the plot.
unit() 用于创建单元对象。这将作为值传递给 panel.spacing。
Syntax : unit(x, unit, data = NULL)
Parameters :
- x : A Numeric Value. Here we want to increase the space between panels from default space to 2 cm. So, here we assign x as 2 .
- unit : A character specifying the units for the corresponding numeric values. Here we use cm unit.
- data : specifying extra information otherwise NULL .
Return : Unit Object
例子:
电阻
# Load Package
library("ggplot2")
# Create a DataFrame
DF <- data.frame(X = rnorm(200),
Y = rnorm(200),
Labels = c("Label 1", "Label 2",
"Label 3", "Label 4"))
# Create a lineplot using ggplot2 with
# 2 cm space between Facet Panels.
ggplot(DF, aes(X, Y)) +
geom_line(color = "dark green") +
facet_grid(Labels ~ .) +
theme(panel.spacing = unit(2, "cm", data = NULL))
输出: