删除ggplot中填充图例的一部分

den*_*nis 0 r data-visualization ggplot2

我在绘图方面遇到了困难:我想删除ggplot绘图中填充图例的一部分,同时保持自动着色。这是一个例子:

library(ggplot2)

df1 <- data.frame(x = 1:20,y1 = rnorm(20,2,0.2),y2 = sqrt(1:20))
df2 <- data.frame(x1 = c(1,5,10),x2 = c(5,10,20),color2 = as.factor(1:3))

ggplot(data=df1) +
  geom_rect(data = df2,
            aes(xmin = x1,
                xmax = x2,
                ymin = 0,
                ymax = Inf,
                fill = color2),
            color = "black",
            size = 0.3,
            alpha = 0.2)+
  geom_bar(aes(x = x,
               y= y1,
               fill = "daily"),
           stat='identity',
           width = 0.75,
           size = 0.1,
           alpha = 0.5) +
  geom_line(aes(x = x,
                y =y2,
                color = "somthing"),
            size = 1.5)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我想要:

  • 仅保留daily填充图例的条目
  • 保持基础上,自动填充color2geom_rect
  • 理想情况下,将两个图例(颜色和填充)合并为一个

我一直在玩scale_fill_manualguide,但我没有带来一些有用的东西。我觉得解决方案可能是制作两个独立的图层并添加它们,但我不知道该怎么做。

有谁知道怎么办?

All*_*ron 5

请记住,您可以breaks在任何比例上设置,因此只需在"daily"填充比例上设置一个中断点。要将它与色标合并(如果我理解你的意思),你可以只给颜色指南和它的单一中断与填充指南和填充中断相同的名称:

ggplot(data=df1) +
  geom_rect(data = df2,
            aes(xmin = x1,
                xmax = x2,
                ymin = 0,
                ymax = Inf,
                fill = color2),
            color = "black",
            size = 0.3,
            alpha = 0.2)+
  geom_bar(aes(x = x,
               y= y1,
               fill = "daily"),
           stat='identity',
           width = 0.75,
           size = 0.1,
           alpha = 0.5) +
  geom_line(aes(x = x,
                y =y2,
                color = "somthing"),
            size = 1.5) +
  scale_fill_discrete(breaks = "daily", name = NULL) +
   scale_color_discrete(name = "labels") +
  theme(legend.margin = margin(0, 0, -10, 0))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明