首页 > 解决方案 > R使用scale_linetype_manual在ggplot图例中旋转vline

问题描述

我有以下简单的 MWE。我希望我的图例中的绿线是一条垂直线。一旦我在 geom_vline 中启用 show.legend,它还会在图例中的每一行添加一条垂直线。有没有人暗示我如何做到这一点?

library(ggplot2)
ggplot(data = df) +
  geom_line(aes(x = a, y = b, colour = "one", linetype = "one"), size = 2) +
  geom_line(aes(x = a, y = c, colour = "two", linetype = "two"), size = 2) +
  geom_vline(aes(xintercept = 0.5, colour = "three", linetype = "three"), alpha = 1, show.legend = F) +
  scale_colour_manual("",
                      breaks = c("one", "two", "three"),
                      values = c("blue", "red", "green")) +
  scale_linetype_manual("",
                        breaks = c("one", "two", "three"),
                        values = c("dashed", "solid", "solid")) +
  theme_bw() +
  theme(legend.key.size = unit(2, "cm"),
        legend.position = c(0.05, 0.995), legend.justification = c(0.05, 0.995))

在此处输入图像描述

标签: rggplot2

解决方案


调整答案以实现您想要的结果的一个选项是使用自定义键字形功能。这种方法的一个缺点是它会根据线的条件在color水平线或垂直线之间进行选择,也就是说,如果您更改颜色,您也必须调整条件。

编辑要在图例中获得正确的线条大小,有两个选项。一种是在自定义键字形函数中设置大小。第二种选择是通过using的override.aes参数设置大小guide_legendguides(linetype = guide_legend(override.aes = list(size = c(2, 2, .5))))

library(ggplot2)

# Custom Key Glyph. Vertical Line if color = "green". Horizontal Line otherwise
draw_key_cust <- function(data, params, size) {
  if (data$colour == "green") {
    data$size <- .5
    draw_key_vpath(data, params, size)
  } else {
    data$size <- 2
    draw_key_path(data, params, size)
  }
}

ggplot(data = df) +
  geom_line(aes(x = a, y = b, colour = "one", linetype = "one"), size = 2, key_glyph = "cust") +
  geom_line(aes(x = a, y = c, colour = "two", linetype = "two"), size = 2, key_glyph = "cust") +
  geom_vline(aes(xintercept = 0.5, colour = "three", linetype = "three"), alpha = 1, key_glyph = "cust") +
  scale_colour_manual(breaks = c("one", "two", "three"),
                      values = c("blue", "red", "green")) +
  scale_linetype_manual(breaks = c("one", "two", "three"),
                        values = c("dashed", "solid", "solid")) +
  labs(color = NULL, linetype = NULL) +
  theme_bw() +
  theme(legend.key.size = unit(2, "cm"),
        legend.position = c(0.05, 0.995), 
        legend.justification = c(0.05, 0.995))

数据

set.seed(42)
df <- data.frame(
  a = runif(100),
  b = runif(100),
  c = runif(100)
)

推荐阅读