ggplot2 自定义几何线字形不正确

问题描述 投票:0回答:1

背景

我正在 R 中为 ggplot2 开发一个自定义几何图形,它首先基于

geom_segment()
:

进行构建
geom_custom <- function(mapping = NULL, data = NULL,
                     stat = "identity", position = "identity",
                     ..., na.rm = FALSE, show.legend = NA,
                     inherit.aes = TRUE) {
  
  out <- layer(
    data = data,
    mapping = mapping,
    stat = stat,
    geom = CustomGeom,
    position = position,
    show.legend = show.legend,
    inherit.aes = inherit.aes,
    params = list(na.rm = na.rm, ...)
  )
  
  out
}

CustomGeom <- ggproto("CustomGeom", Geom,
                    required_aes = c("x", "y", "xend"),
                    non_missing_aes = c("linetype", "linewidth"),
                    default_aes = aes(
                      colour = "black",
                      linewidth = 2,
                      size = 2,
                      linetype = 1,
                      alpha = NA
                    ),
                    draw_panel = function(data, panel_params, coord, ...) {
                      
                      # Return all components
                      grid::gList(
                        GeomSegment$draw_panel(data, panel_params, coord, ...)
                      )
                    }
)

问题

问题是图例字形错误地显示了形状值,而不是

geom_segment()
通常给出的线条。这是一个示例表示和输出:

df <- tibble::tribble(
  ~"record", ~"status", ~"start_time", ~"end_time",
  1, "status1", 0, 5,
  2, "status1", -2, 7,
  3, "status2", 2, 15
)

ggplot() +
  geom_custom(data = df,
              mapping = aes(x = start_time, xend = end_time, y = record, colour = status))

enter image description here

以及使用

geom_segment()
的预期输出:

enter image description here

关于如何纠正这里的图例字形有什么建议吗?

谢谢!

r ggplot2 geom-segment
1个回答
0
投票

我相信我已经通过在图层定义中设置

key_glyph = "path"
找到了解决方案:

geom_custom <- function(mapping = NULL, data = NULL,
                     stat = "identity", position = "identity",
                     ..., na.rm = FALSE, show.legend = NA,
                     inherit.aes = TRUE) {
  
  out <- layer(
    data = data,
    mapping = mapping,
    stat = stat,
    geom = CustomGeom,
    position = position,
    show.legend = show.legend,
    inherit.aes = inherit.aes,
    key_glyph = "path",
    params = list(na.rm = na.rm, ...)
  )
  
  out
}

我仍然对为什么图例字形首先根据原始代码进行更改感到困惑,如果有人有更多的见解,我很乐意接受新的答案。但目前这似乎适合我的用例。

© www.soinside.com 2019 - 2024. All rights reserved.