ggplot2:组合颜色和填充图例,legend.key边框

时间:2018-06-25 10:23:23

标签: r ggplot2

我正在尝试制作数字条形图,并带有重叠线和利率的置信区间。我希望图例有意义,例如,一条对应条,一条对应于线和置信区间。

这是我到目前为止所掌握的。除了速率图例键周围的红色边框以外,它几乎是完美的。我无法弄清楚如何在不删除线条的情况下删除边框。我想念什么吗?我要对图例的整个构造做错吗?我以前从未使用过scale_xxx_identity(),而且我的所作所为似乎有点破烂,所以我愿意接受其他选择。

library(tidyverse)

test <- tibble(year = 2001:2010,
               number = 20:29,
               rate = 0.02,
               rate_l = 0.015,
               rate_u = 0.025)

secondAxisFactor <- 500

test %>% 
    ggplot(aes(factor(year), number)) +
    geom_col(aes(fill = "turquoise",
                 colour = "transparent")) +
    geom_ribbon(aes(ymin = rate_l * secondAxisFactor,
                    ymax = rate_u * secondAxisFactor,
                    group = 1,
                    fill = "pink"),
                alpha = 0.8) +
    geom_line(aes(y = rate * secondAxisFactor,
                  group = 1,
                  colour = "red"),
              size = 1) +
    scale_fill_identity(name = NULL,
                        guide = "legend",
                        breaks = c("turquoise", "pink"),
                        labels = c("Number", "Rate (95% CI)")) +
    scale_color_identity(name = NULL,
                         guide = "legend",
                         breaks = c("transparent", "red"),
                         labels = c("Number", "Rate (95% CI)"))

first try: red border around colour fill

我还尝试过仅对条形使用填充图例,对线仅具有彩色图例,然后在legend.key中将theme()填充设置为粉红色。 几乎也可以,但是粉红色从绿松石的后面露出来。也许有办法解决这个问题?

test %>% 
    ggplot(aes(factor(year), number)) +
    geom_col(aes(fill = "turquoise")) +  # removed transparent
    geom_ribbon(aes(ymin = rate_l * secondAxisFactor,
                    ymax = rate_u * secondAxisFactor,
                    group = 1),  # pink not in aes()
                fill = "pink",
                alpha = 0.8) +
    geom_line(aes(y = rate * secondAxisFactor,
                  group = 1,
                  colour = "red"),
              size = 1) +
    scale_fill_identity(name = NULL,
                        guide = "legend",
                        # fill legend only for bars
                        breaks = c("turquoise"),
                        labels = c("Number")) +
    scale_color_identity(name = NULL,
                         guide = "legend",
                         # colour legend only for line
                         breaks = c("red"),
                         labels = c("Rate (95% CI)")) +
    # setting legend.key fill to pink
    theme(legend.key = element_rect(fill = "pink"))

second try: pink background behind fill legend

0 个答案:

没有答案