如何更改ggplot对象条带区域某些边框的颜色?
How to change color of certain border of strip area of ggplot object?
剧情代码:
library(tidyverse)
mtcars %>%
ggplot(aes(factor(cyl), disp)) +
geom_col() +
facet_grid(. ~ gear, switch = "x") +
theme(
strip.placement = "outside",
strip.background = element_rect(fill = "white", color = "red")
)
我正在尝试修改某些边框的颜色:
预期输出:
我尝试使用 grobs 更改它,但似乎无法更改特定边框。
p <- mtcars %>%
ggplot(aes(factor(cyl), disp)) +
geom_col() +
facet_grid(. ~ gear, switch = "x") +
theme(
strip.placement = "outside",
strip.background = element_rect(fill = "white", color = "red")
)
g <- ggplotGrob(p)
g$grobs[[13]]$grobs[[1]]$children$strip.background.x..rect.33641$gp$col
根据 的回答,您可以使用 linesGrob
更改边框。在您的情况下,您将需要 polylineGrob
因为您需要两条未连接的线(在网格的每一侧各一条)。
代码
p <- mtcars %>%
ggplot(aes(factor(cyl), disp)) +
geom_col() +
facet_grid(. ~ gear, switch = "x") +
theme(
strip.placement = "outside",
strip.background = element_rect(color = NA)
)
library(grid)
q <- ggplotGrob(p)
lr2 <- polylineGrob(x=c(0,0,1,1),
y=c(0,1,0,1),
id=c(1,1,2,2),
gp=gpar(col="blue", lwd=3))
for (k in grep("strip-b",q$layout$name)) {
q$grobs[[k]]$grobs[[1]]$children[[1]] <- lr2
}
grid.draw(q)
情节
剧情代码:
library(tidyverse)
mtcars %>%
ggplot(aes(factor(cyl), disp)) +
geom_col() +
facet_grid(. ~ gear, switch = "x") +
theme(
strip.placement = "outside",
strip.background = element_rect(fill = "white", color = "red")
)
我正在尝试修改某些边框的颜色: 预期输出:
我尝试使用 grobs 更改它,但似乎无法更改特定边框。
p <- mtcars %>%
ggplot(aes(factor(cyl), disp)) +
geom_col() +
facet_grid(. ~ gear, switch = "x") +
theme(
strip.placement = "outside",
strip.background = element_rect(fill = "white", color = "red")
)
g <- ggplotGrob(p)
g$grobs[[13]]$grobs[[1]]$children$strip.background.x..rect.33641$gp$col
根据 linesGrob
更改边框。在您的情况下,您将需要 polylineGrob
因为您需要两条未连接的线(在网格的每一侧各一条)。
代码
p <- mtcars %>%
ggplot(aes(factor(cyl), disp)) +
geom_col() +
facet_grid(. ~ gear, switch = "x") +
theme(
strip.placement = "outside",
strip.background = element_rect(color = NA)
)
library(grid)
q <- ggplotGrob(p)
lr2 <- polylineGrob(x=c(0,0,1,1),
y=c(0,1,0,1),
id=c(1,1,2,2),
gp=gpar(col="blue", lwd=3))
for (k in grep("strip-b",q$layout$name)) {
q$grobs[[k]]$grobs[[1]]$children[[1]] <- lr2
}
grid.draw(q)
情节