在 ggplot 中显示填充箭头图例

3
我试图绘制一条带有箭头的线段,并使它在图例中显示。我可以通过以下代码实现:
library(ggplot2)

# sample data
dat <- data.frame(
  x = as.factor(1:10),
  y = c(20,30,13,37,12,50,31,2,40,30),
  z = rep('a', 10)
)

# basic plot
ggplot(dat) +
  geom_segment(
    aes(x = x, xend = x, y = 0, yend = y+15, linetype = z), 
    arrow = arrow(length = unit(0.25, 'cm'), type = 'closed'),
    size = 0.7
  ) 

输出:

输入图像说明

问题:

我的问题是图例中的箭头不像图形一样填充。我尝试使用 guide_legend(override.aes = aes(fill='black'))guide_legend(override.aes = aes(type='closed')),但对图例没有任何影响。

有人知道如何制作黑色实心三角形吗?

编辑:

我有一个类似的问题,geom_label 中的标签周围没有黑色线条出现在图例中。我设法通过在我想要的确切位置添加一个 geom_rect 来解决这个问题,但希望这不是最好的解决方案:P

任何一个问题的解决方案都会非常有帮助!

输入图像说明


似乎这是一个已知的问题:https://github.com/tidyverse/ggplot2/issues/3455。希望在下一次更新中解决。 - morgan121
1个回答

6
自ggplot2 3.2.0版本开始,可以提供自定义图例绘制函数。因此,如果图例看起来不太对,您始终可以从ggplot2代码库中复制相应的图例绘制函数,然后根据需要进行修改。
library(ggplot2)
library(grid)
library(rlang)

# legend drawing function, copied from ggplot2
draw_key_segment_custom <- function(data, params, size) {
  if (is.null(data$linetype)) {
    data$linetype <- 0
  } else {
    data$linetype[is.na(data$linetype)] <- 0
  }

  segmentsGrob(0.1, 0.5, 0.9, 0.5,
    gp = gpar(
      col = alpha(data$colour %||% data$fill %||% "black", data$alpha),
      # the following line was added relative to the ggplot2 code
      fill = alpha(data$colour %||% data$fill %||% "black", data$alpha),
      lwd = (data$size %||% 0.5) * .pt,
      lty = data$linetype %||% 1,
      lineend = "butt"
    ),
    arrow = params$arrow
  )
}


# sample data
dat <- data.frame(
  x = as.factor(1:10),
  y = c(20,30,13,37,12,50,31,2,40,30),
  z = rep('a', 10)
)

# basic plot
ggplot(dat) +
  geom_segment(
    aes(x = x, xend = x, y = 0, yend = y+15, linetype = z), 
    arrow = arrow(length = unit(0.25, 'cm'), type = 'closed'),
    size = 0.7,
    key_glyph = "segment_custom"
  ) 

使用reprex包(v0.3.0)于2019-07-25创建


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接