根据分面图中的数据计算轴刻度位置

Calculate axis tick locations based on data in faceted plot

我有一个问题,我想在 facet_grid() 的大图中计算 y 轴标签的位置。让我用 mpg 数据集告诉你我的意思。

require(tidyverse)

ggplot(mpg, aes(x = displ)) +
  geom_point(aes(y = hwy)) +
  facet_grid(drv ~ class, scales = "free")

您会注意到两个轴都使用可变数量的标签。忽略 x 轴的问题,我感兴趣的是在 y 轴上只标记三个值:0、最大值的一半和最大值。这在我的用例中很有意义,所以这是我尝试过的。

ggplot(mpg, aes(x = displ)) +
  geom_point(aes(y = hwy)) +
  facet_grid(drv ~ class, scales = "free") +
  geom_blank(aes(y = 0)) +                                 # extends y-axis to 0
  scale_y_continuous(expand = expansion(mult = c(0, 0.1)), # prevents ggplot2 from extending beyond y = 0
                     n.breaks = 3)                         # Three axis labels, please.

绘图正确地从 y = 0 开始并正确地标记了它。但是,剩余的标签分配不当,并且由于某种原因具有标签 n = 2n = 4 而不是 n = 3

要是能直接计算标签位置就好了!

ggplot(mpg, aes(x = displ)) +
  geom_point(aes(y = hwy)) +
  facet_grid(drv ~ class, scales = "free") +
  geom_blank(aes(y = 0)) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.1)),
                     n.breaks = 3,
                     breaks = c(0, 0.5*max(hwy), 1*max(hwy))) # Maybe these formulas works?
Error in check_breaks_labels(breaks, labels) : object 'hwy' not found

我认为通过这种方式提供断点应该可行,但我的语法很糟糕。我如何访问和使用图下的数据?或者,如果这不起作用,我可以手动为每一行面板指定 y 轴标签吗?

拜托,我真的需要一些帮助。

你可以删除scales free:你得到你想要的了吗?

require(tidyverse)

ggplot(mpg, aes(x = displ)) +
  geom_point(aes(y = hwy)) +
  facet_grid(drv ~ class)

如果您想要自定义休息规则,最简单的方法是在给定(面板)限制的情况下使用实现这些规则的函数。

下面是标记 0、最大值和半最大值的示例。

library(ggplot2)

ggplot(mpg, aes(x = displ)) +
  geom_point(aes(y = hwy)) +
  facet_grid(drv ~ class, scales = "free") +
  scale_y_continuous(expand = expansion(mult = c(0, 0.1)),
                     limits = c(0, NA), # <- fixed min, flexible max. replaces geom_blank
                     breaks = function(x){c(x[1], mean(x), x[2])})