R语言 如何移除ggplot2图例标注周围的框

0ejtzxu1  于 2023-01-03  发布在  其他
关注(0)|答案(2)|浏览(527)

我有一个折线图,在数据的第一和第三四分位数之间有一个带状图。当我用ggplot2绘制数据时,我在标签周围得到了一些框,无论我怎么尝试都无法去掉这些框(即主题(legend.background=element_blank())或带覆盖的指南(guides_legend))。dataframe以下是我的数据集和代码的前几行:

mutate(code_range = fct_reorder2(code_range, year, order)) %>% 
  ggplot(aes(x=year, y=value, group=code_range, color=code_range)) +
  geom_ribbon(aes(ymin = min_range, 
                  ymax = max_range), fill = "grey70", alpha=0.1) +
  geom_line(size=1) +
  labs(title="Title", 
       subtitle=paste0("subtitle"),
       x="",y="",
       caption="Source") +
  scale_colour_manual(values = c("min" = "#878787", "q1" = "#B5B5B5", "median" = "#27408B", 
                                 "q3" = "#B5B5B5", "max" = "#878787")) +
  scale_fill_manual(values = c("min" = "#FFFFFF", "q1" = "#B5B5B5", "median" = "#27408B", 
                               "q3" = "#B5B5B5", "max" = "#878787")) +
  theme_opts +
  theme(legend.title = element_blank(), 
        legend.position = "bottom") +
  theme(legend.background=element_blank()) 
plot

有谁知道怎么把那些盒子搬走吗?

pjngdqdw

pjngdqdw1#

图例键周围的框反映了geom_ribbon。要删除它们,可以将show.legend=FALSE添加到geom_ribbon
使用一些虚假的示例数据:

library(ggplot2)

df <- data.frame(
  year = 2005:2020,
  value = 1:16,
  min_range = 1:16 - 1,
  max_range = 1:16 + 1
)

base <- ggplot(df, aes(year, value, color = "median")) +
  geom_line() +
  scale_colour_manual(values = c(
    "min" = "#878787", "q1" = "#B5B5B5", "median" = "#27408B",
    "q3" = "#B5B5B5", "max" = "#878787"
  ))

首先重现您的问题:

base +
  geom_ribbon(aes(ymin = min_range, ymax = max_range), fill = "grey70", alpha = 0.1)

其次,使用show.legend = FALSE

base +
  geom_ribbon(aes(ymin = min_range, ymax = max_range), fill = "grey70", alpha = 0.1, show.legend = FALSE)

dsf9zpds

dsf9zpds2#

另一种选择是仅将颜色美感移动到geom_line

library(ggplot2)

p <- ggplot(iris, aes(Sepal.Length, Petal.Width, color = Species)) +
  geom_smooth()

df_p <- layer_data(p)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

## something similar to your plot
ggplot(df_p, aes(color = as.character(group))) + 
  geom_ribbon(aes(x = x, ymin = ymin, ymax = ymax)) +
  geom_line(aes(x, y))

## change the location of your color aesthetic to geom_line only
## you need to add a grouping aesthetic into the ribbon call
ggplot(df_p) + 
  geom_ribbon(aes(x = x, ymin = ymin, ymax = ymax, group = as.character(group))) +
  geom_line(aes(x, y, color = as.character(group)))

创建于2023年1月2日,使用reprex v2.0.2

相关问题