首页 > 解决方案 > ggplot2:如何让 Geom 类影响 ScaleContinuous 类

问题描述

我已经开始扩展ggplot2,我仍然对包如何调用它的所有内部函数有所了解。

我有一个新的 ggproto 类,它扩展了当前Geom环境之一。类的当前模型将沿着离散的 x 轴绘制一些东西,理想情况下接触 x 轴刻度。当 y 轴已经处于离散比例时,此模型运行良好,因为默认扩展值仅添加 0.6 填充。然而,在连续的 y 尺度上,默认填充可以使这些新绘制的对象看起来很远。总之,我怎样才能让我的Geom类覆盖默认扩展而不只是添加scale_y_continuous(expand = c(0,0,.05,0)或添加scale_y_discrete(expand = c(0, 0, .6,0)到我的图层功能......

考虑以下可重现的示例

library(dplyr)
library(tidyr)
library(ggplot2)
library(stringr)
mtcars0 <- as_tibble(mtcars, rownames = "CarNames") %>%
  gather(key = "qualities", value = "value", -CarNames) %>%
  group_by(qualities) %>%
  mutate(scaledValue = scale(value)) %>%
  ungroup() %>%
  mutate(carCase = case_when(str_detect(CarNames, "^[A-M]") ~ "A-M",
                             TRUE ~ "N-Z"))
"%||%" <- function(a, b) {
  if (!is.null(a)) a else b
}

MyText <- ggproto("GeomMyText",
                  GeomText,
                  extra_params = c("na.rm","padDist"),
                  setup_data = function(data, params){
                    #find bottom of plot with sufficent space
                    minpadding <- params$padDist %||% diff(range(data$y))*.05
                    data$y <- min(data$y) - minpadding
                    data 
                  })

geom_mytext <- function (mapping = NULL, data = NULL, stat = "identity", position = "identity", 
                         ..., parse = FALSE, nudge_x = 0, nudge_y = 0, check_overlap = FALSE, 
                         na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, padDist = NULL) 
{ 
  if (!missing(nudge_x) || !missing(nudge_y)) {
    if (!missing(position)) {
      abort("You must specify either `position` or `nudge_x`/`nudge_y`.")
    }
    position <- position_nudge(nudge_x, nudge_y)
  }
  layer(data = data, mapping = mapping, stat = stat, geom = MyText, 
        position = position, show.legend = show.legend, inherit.aes = inherit.aes, 
        params = list(parse = parse, check_overlap = check_overlap, 
                      na.rm = na.rm, padDist = padDist, ...))
}


result <- ggplot(mtcars0, aes(x = CarNames, value)) +
  geom_point() +
  geom_mytext(aes(label = carCase)) +
  theme(axis.text.x = element_text(angle=90))
#Default
result 
#Desired Result without having to call scale_y_continuous
result + scale_y_continuous(expand = c(0,0,0.05,0))

我假设我需要扩展ScaleContinuous环境,但我不知道如何将MyText环境与它连接起来。

有什么建议么?

- - 编辑 - -

感谢您的快速回复!一些东西 -

  1. 我知道标签的绘制和剪裁过度,这不是我实际的 Geom 环境,只是我可以放在一起的东西来证明我的问题。
  2. 正如我所担心的,到目前为止,似乎每个人都在提供针对这个问题提出的解决方案。虽然提供我自己的比例不太理想 - 因为我必须投入逻辑来辨别它们关联的 y 轴是否是离散/连续的,当ggplot2已经知道这一点时,我认为可能有一个我错过的技巧。现在,我将根据给出的建议继续开发。谢谢!

---- 编辑 2 ----

我又看了看这里给出的解决方案。我需要修改的确切参数是

panel_params$y$continuous_range[1] <- panel_params$y$limits[1]

我需要在draw_panel. 似乎相关的比例包含在那里,并且coord$transform(data, panel_params)负责在重新缩放的轴上包含填充,具体取决于为panel_params$y$limits和设置的内容panel_params$y$continuous_range

再次感谢所有贡献的人!

标签: rggplot2environmentreference-class

解决方案


好问题 - 感谢您的发帖。

这比你想象的要容易。geom_mytext您只需将所需的比例对象与从您的函数返回的图层对象捆绑在一起,方法是将它们与c. 在此示例中,我还捆绑了一个coord_cartesian对象,以便我可以关闭剪切以正确显示文本。我还将默认设置更改为check.overlapTRUE因为您的标签被过度绘制。

注意我根本没有改变你的ggplot电话

geom_mytext <- function (mapping = NULL, data = NULL, stat = "identity", position = "identity", 
                         ..., parse = FALSE, nudge_x = 0, nudge_y = 0, check_overlap = FALSE, 
                         na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, padDist = NULL) 
{ 
  if (!missing(nudge_x) || !missing(nudge_y)) {
    if (!missing(position)) {
      abort("You must specify either `position` or `nudge_x`/`nudge_y`.")
    }
    position <- position_nudge(nudge_x, nudge_y)
  }
  c(layer(data = data, mapping = mapping, stat = stat, geom = MyText, 
        position = position, show.legend = show.legend, inherit.aes = inherit.aes, 
        params = list(parse = parse, check_overlap = check_overlap, 
                      na.rm = na.rm, padDist = padDist, ...)), 
    scale_y_continuous(expand = c(0,0,0.05,0)),
    coord_cartesian(clip = "off"))
}


result <- ggplot(mtcars0, aes(x = CarNames, value)) +
  geom_point() +
  geom_mytext(label = "test") +
  theme(axis.text.x = element_text(angle=90))

result 

在此处输入图像描述

现在是警告。因为您正在提供自己的scale_y_continuous对象,所以用户不会喜欢 ggplot 在尝试添加自己的 y 比例时抱怨。您还需要一些逻辑来在添加连续或离散 y 刻度之间进行选择。我不认为这些是不可克服的问题。


推荐阅读