卸下传奇符号的边界卸下传奇符号的边界(Removing the border of legend s

2019-05-12 08:44发布

我想要绘制一些预测与实际数据,一些类似于如下:

# Some random data
x <- seq(1: 10)
y_pred <- runif(10, min = -10, max = 10)
y_obs <- y_pred + rnorm(10)
# Faking a CI
Lo.95 <- y_pred - 1.96
Hi.95 <- y_pred + 1.96
my_df <- data.frame(x, y_pred, y_obs, Lo.95, Hi.95)

ggplot(my_df, aes(x = x, y = y_pred)) +
  geom_line(aes(colour = "Forecasted Data"), size = 1.2) +
  geom_point(aes(x = x, y = y_obs, colour = "Actual Data"), size = 3) +
  geom_ribbon(aes(ymin=Lo.95, ymax=Hi.95, x=x, linetype = NA,  colour = "Confidence Interval"), alpha=0.2) +
  theme_grey() +
  scale_colour_manual(
    values = c("gray30", "blue", "red"),
    guide = guide_legend(override.aes = list(
      border=c(NA, NA, NA), 
      fill=c("gray30", "white", "white"),
      linetype = c("blank", "blank", "solid"),
      shape = c(NA, 19, NA)))) 

情节是这样的:

我有这个情节的唯一问题是围绕该行的图例项符号(即预测数据)的红色边框。 有没有什么办法可以删除它没有打破我的阴谋的休息吗?

Answer 1:

我认为geom_ribbon是问题。 如果我们把它的colorfill出来的aes ,一切都看起来不错

library(ggplot2)

# Some random data
x <- seq(1: 10)
y_pred <- runif(10, min = -10, max = 10)
y_obs <- y_pred + rnorm(10)
# Faking a CI
Lo.95 <- y_pred - 1.96
Hi.95 <- y_pred + 1.96
my_df <- data.frame(x, y_pred, y_obs, Lo.95, Hi.95)

m1 <- ggplot(my_df, aes(x = x, y = y_pred)) +
  geom_point(aes(x = x, y = y_obs, colour = "Actual"), size = 3) +
  geom_line(aes(colour = "Forecasted"), size = 1.2) +
  geom_ribbon(aes(x = x, ymin = Lo.95, ymax = Hi.95), 
              fill = "grey30", alpha = 0.2) +
  scale_color_manual("Legend", 
                     values = c("blue", "red"),
                     labels = c("Actual", "Forecasted")) +
  guides( color = guide_legend(
    order = 1,
    override.aes = list(
                        color = c("blue", "red"),
                        fill  = c("white", "white"),
                        linetype = c("blank", "solid"),
                        shape = c(19, NA)))) +
  theme_bw() +
  # remove legend key border color & background
  theme(legend.key = element_rect(colour = NA, fill = NA),
    legend.box.background = element_blank())
m1

当我们离开Confidence Interval出的aes ,我们不再有它的传说。 一个解决方法是创建一个不可见的点,并采取一个未使用geom手动创建图例键。 这里我们可以使用size/shape (信贷这个答案 )

m2 <- m1 +
  geom_point(aes(x = x, y = y_obs, size = "Confidence Interval", shape = NA)) +
  guides(size = guide_legend(NULL, 
                             order = 2,
                             override.aes = list(shape = 15, 
                                                 color = "lightgrey",
                                                 size = 6))) +
  # Move legends closer to each other
  theme(legend.title = element_blank(),
        legend.justification = "center",
        legend.spacing.y = unit(0.05, "cm"),
        legend.margin = margin(0, 0, 0, 0),
        legend.box.margin = margin(0, 0, 0, 0)) 
m2

由创建于2018年3月19日reprex包 (v0.2.0)。



文章来源: Removing the border of legend symbol
标签: r ggplot2