gpt4 book ai didi

r - ggplot2 facet wrap : y-axis scale on the first row only

转载 作者:行者123 更新时间:2023-12-04 11:33:24 31 4
gpt4 key购买 nike

是否可以将 y 轴添加到 facet wrap,但仅限于第一行,如屏幕截图所示?

我的情节代码:

library(ggplot2)

mydf <- read.csv('https://dl.dropboxusercontent.com/s/j3s5sov98q9yvcv/BPdf_by_NB')

ggplot(data = mydf) +
geom_line(aes(x = YEARMONTH, y = NEWCONS, group = 1), color="darkseagreen3") +
geom_line(aes(x = YEARMONTH, y = DEMOLITIONS, group = 1), color = "black") +
theme_minimal() +
labs(title="New constructions Vs Demolitions (2010 - 2014)\n") +
theme( axis.line = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank()) +
facet_wrap(~ NB)

结果:

ggplot2 facet wrap

(我已手动为要放置比例的位置添加了图例)

最佳答案

这个想法来自 this回答。

p <- ggplot(data = mydf) +
geom_line(aes(x = YEARMONTH, y = NEWCONS, group = 1), color="darkseagreen3") +
geom_line(aes(x = YEARMONTH, y = DEMOLITIONS, group = 1), color = "black") +
theme_minimal() +
labs(title="New constructions Vs Demolitions (2010 - 2014)\n") +
theme( axis.line = element_blank(),
axis.title.x = element_blank(),
axis.text.x = element_blank()) +
facet_wrap(~ NB)

请注意 theme 中的更改调用,以便我们以后可以选择性地删除一些grob。
library(gtable)
p_tab <- ggplotGrob(p)
print(p_tab)

所以我们想要移除除了四个左轴项之外的所有项。有一个 gtable_filter函数使用正则表达式,但编写自己的函数来执行简单的负子集更简单(因为我无法制作正确的正则表达式):
gtable_filter_remove <- function (x, name, trim = TRUE){
matches <- !(x$layout$name %in% name)
x$layout <- x$layout[matches, , drop = FALSE]
x$grobs <- x$grobs[matches]
if (trim)
x <- gtable_trim(x)
x
}

p_filtered <- gtable_filter_remove(p_tab,name = paste0("axis_l-",5:16),trim=FALSE)

library(grid)
grid.newpage()
grid.draw(p_filtered)

enter image description here

关于r - ggplot2 facet wrap : y-axis scale on the first row only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36779537/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com