我开始使用 ale 包从模型自动生成 ggplot 对象。我想删除使用 hlines 自动创建的标签“75%”、“中位数”和“25%”:这是我的图表。 我发现它使图表过于拥挤(因为我将 6 个图与 wrap_plots 结合在一起),并且可以轻松地在图表下方的图例中以文本方式解释它们。有没有办法做到这一点?我不是 ggplot 专家,在这方面花了太多时间,请帮忙:')
我将 6 个图存储在名为“list”的列表中,然后使用 wrap_plots。我可以使用以下代码自定义 x 轴标签:
列表[[“plot1”]][[“标签”]][[“x”]] <- "Degree Days"
它有效,但我似乎找不到“75%”、“中位数”和“25%”标签存储在 ggplot 对象中的位置,可能是因为它们不是标签?
这是我从 ale 包文档中复制的示例:
diamonds_sample <- ggplot2::diamonds[sample(nrow(ggplot2::diamonds), 1000), ]
# Create a GAM model
gam_diamonds <- mgcv::gam(
price ~ s(carat) + s(depth) + s(table) + s(x) + s(y) + s(z) +
cut + color + clarity,
data = diamonds_sample
)
summary(gam_diamonds)
# Simple ALE
ale_gam_diamonds <- ale(
diamonds_sample, gam_diamonds,
parallel = 2 # CRAN limit (delete this line on your own computer)
)
# Plot the ALE data
ale_gam_diamonds$plots |>
patchwork::wrap_plots()
水平线的标签是通过辅助轴添加的。因此,摆脱这些标签的一种选择是覆盖 y 比例。
当您想要将修改应用于所有绘图时,通常无需摆弄
list
对象的 ggplot
。相反,您可以将修改应用于最终的 patchwork
对象。
实际上,获得图例需要付出更多努力(见下文)。作为第一种方法,您可能会考虑通过去掉内部绘图的轴来整理绘图,使用
patchwork >=1.2.0
可以通过使用 axes="collect"
来实现。
library(ale)
library(patchwork)
library(ggplot2)
# Get rid of the axes for the inner plots
ale_gam_diamonds$plots |>
wrap_plots() +
plot_layout(axes = "collect") &
labs(x = "Degree Days")
但如果你更喜欢有一个图例,你可以通过添加一个空白(例如
geom_hline
)图层来伪造一个图例,我决定在linetype
aes 上进行映射。之后,您可以使用“override.aes”参数设置图例的样式:
# Use a legend
ale_gam_diamonds$plots |>
wrap_plots() +
plot_layout(guides = "collect") &
labs(x = "Degree Days", linetype = NULL) &
# Get rid of the secondary axis aka the labels on the right
scale_y_continuous() &
# Fake a legend
geom_hline(
data = data.frame(
yintercept = NA_real_,
linetype = factor(c("25%", "median", "75%"), c("25%", "median", "75%"))
),
aes(yintercept = yintercept, linetype = linetype),
na.rm = TRUE
) &
guides(
linetype = guide_legend(
override.aes = list(
color = c("black", "grey85", "black"),
linetype = c("dashed", "solid", "dashed")
)
)
) &
theme(legend.position = "bottom")
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.