sho*_*eth 3 r facet ggplot2 facet-wrap
我创建了一个多面图facet_wrap
,并且我想更改所有面的 y 轴的中断。
这是我当前的情节:
ggplot( mtcars , aes(x=mpg, y=wt, color=as.factor(cyl) )) +
geom_point(size=3) +
facet_wrap(~cyl,scales = "free_y") +
theme(legend.position="none")
Run Code Online (Sandbox Code Playgroud)
这是我想要的 y 轴中断:
p = ggplot(data=mtcars, aes(x=mpg, y=wt)) +
geom_point(size=3) +
theme_classic()
ymax <- ceiling(max(mtcars$wt))
p + scale_y_continuous(breaks = c(0, ymax), expand = c(0, 0)) + expand_limits(y = ymax)
Run Code Online (Sandbox Code Playgroud)
teu*_*and 12
如果您有 y 轴中断/限制的“规则”,您可以为比例的这些参数提供一个函数,该函数将为每个方面评估该函数。请注意,该limits
函数获取“自然”数据限制作为参数,而该breaks
函数获取扩展限制作为参数。
library(ggplot2)
p <- ggplot( mtcars , aes(x=mpg, y=wt, color=as.factor(cyl) )) +
geom_point(size=3) +
facet_wrap(~cyl,scales = "free_y") +
theme(legend.position="none")
p + scale_y_continuous(
limits = ~ c(min(.x), ceiling(max(.x))),
breaks = ~ .x[2],
expand = c(0, 0)
)
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要调整每个面板的 y 轴,您可能会发现ggh4x::facetted_pos_scales()
很有用。免责声明:我是 ggh4x 的作者。
p + ggh4x::facetted_pos_scales(y = list(
cyl == 4 ~ scale_y_continuous(limits = c(0, NA)),
cyl == 6 ~ scale_y_continuous(breaks = c(2.9, 3, 3.1)),
cyl == 8 ~ scale_y_continuous(trans = "reverse")
))
Run Code Online (Sandbox Code Playgroud)
由reprex 包于 2022 年 7 月 16 日创建(v2.0.1)