将根据这些数据绘制一个图:
library(ggplot2)
mtcars %>%
gather(-mpg, key = "var", value = "value") %>%
ggplot(aes(x = value, y = mpg)) +
geom_point() +
facet_wrap(~ var, scales = "free") +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
例如,如何更改面板标题的灰色
添加图例
不幸的是,回答OP问题的方法似乎仍然很棘手。
如果你不喜欢像那些引用的那样的gtable hacks ...这里有另一种异常 hacky 的方法来做到这一点。享受奇怪的旅程。
TL;DR - 这里的想法是使用绘图区域之外的矩形几何图形来绘制每个面标签框的颜色
这是下面的基本情节。OP想要(1)根据分面标签将分面标签(称为“条带”标签)后面的灰色更改为特定颜色,然后(2)添加图例。
首先,我只是将收集的数据帧引用为df
,所以绘图代码现在看起来像这样:
df <- mtcars %>% gather(-mpg, key = "var", value = "value")
ggplot(df, aes(x = value, y = mpg)) +
geom_point() +
facet_wrap(~ var, scales = "free") +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
theme()
正如其他答案中所引用的,通过元素strip.background
和一次更改所有方面标签颜色(和方面标签文本)非常简单strip.text
:
plot + theme(
strip.background = element_rect(fill="blue"),
strip.text=element_text(color="white"))
Run Code Online (Sandbox Code Playgroud)
当然,我们不能对所有方面标签都这样做,因为strip.background
和element_rect()
不能发送矢量或将映射应用于美学。
这里的想法是,我们使用可以将美学映射到数据的东西(因此根据数据进行更改) - 使用几何。在这种情况下,我将geom_rect()
在每个方面绘制一个矩形,然后根据问题中的标准 OP 状态对该矩形进行着色。此外,geom_rect()
以这种方式使用还会自动为我们创建图例,因为我们将使用映射并aes()
指定颜色。我们需要做的就是允许ggplot2
在绘图区域之外绘制图层,使用一些手动微调来获得正确的位置,并且它可以工作!
首先,创建一个单独的数据集,其中包含名为 的列var
,其中包含所有构面名称。然后var_color
指定 OP 为每个方面指定的名称。我们使用scale_fill_manual()
函数指定颜色。最后,这里要小心使用,这一点很重要coord_cartesian()
。我们需要这个函数有两个原因:
剪切图中的面板区域以仅包含点。如果我们没有指定 y 限制,面板将自动调整大小以适应矩形几何。
关闭剪辑。这使得在面板外部绘制的图层可以被看到。
然后我们需要变成strip.background
透明(这样我们就可以看到盒子的颜色),我们就可以开始了。希望大家能够跟随下面的脚步。
为了更加清晰起见,我代表了下面的所有代码:
library(ggplot2)
library(tidyr)
library(dplyr)
# dataset for plotting
df <- mtcars %>% gather(-mpg, key = "var", value = "value")
# dataset for facet label colors
hacky_df <- data.frame(
var = c("am", "carb", "cyl", "disp", "drat", "gear", "hp", "qsec", "vs", "wt"),
var_color = c("area", "indus", "indus", "bat", "bat", "bat", "area", "indus", "vege", "vege")
)
# plot code
plot_new <-
ggplot(df) + # don't specify x and y here. Otherwise geom_rect will complain.
geom_rect(
data=hacky_df,
aes(xmin=-Inf, xmax=Inf,
ymin=36, ymax=42, # totally defined by trial-and-error
fill=var_color, alpha=0.4)) +
geom_point(aes(x = value, y = mpg)) +
coord_cartesian(clip="off", ylim=c(10, 35)) +
facet_wrap(~ var, scales = "free") +
scale_fill_manual(values = c("area" = "green", "bat" = "red", "vege" = "blue", "indus" = "black")) +
theme_bw() +
theme(
strip.background = element_rect(fill=NA),
strip.text = element_text(face="bold")
)
plot_new
Run Code Online (Sandbox Code Playgroud)