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

问题描述

我有一个问题,我想用 facet_grid() 计算大图中 y 轴标签的位置。让我向您展示我使用 mpg 数据集的意思。

require(tidyverse)

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

enter image description here

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

ggplot(mpg,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.

enter image description here

绘图正确地从 y = 0 开始并正确标记它。但是,其余标签分配不当,并且出于某种原因使用标签 n = 2n = 4 而不是 n = 3

如果我只能直接计算标签位置就好了!

ggplot(mpg,scales = "free") +
  geom_blank(aes(y = 0)) +
  scale_y_continuous(expand = expansion(mult = c(0,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 轴标签吗?

我真的可以在这里寻求帮助。

解决方法

如果您想要自定义中断规则,最简单的方法是使用一个函数来实现给定(面板)限制的这些规则。

下面是标记 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])})

,

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

require(tidyverse)

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

enter image description here