Reputation: 5673
I am facing a difficulty for a plot: I want to remove a part of a fill legend in a ggplot
plot, while keeping the automated coloring. here is an example:
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)
I would like to:
daily
entry of the fill legendcolor2
for the geom_rect
I have been playing around with scale_fill_manual
and guide
, but I did not come with something working. I feel that the solution could be making two independent layer and add them, but I don't know how to do that.
Does anyone know how to do ?
Upvotes: 0
Views: 1615
Reputation: 173793
Remember you can set the breaks
on any scale, so just set a single break at "daily"
on your fill scale. To merge it with the color scale (if I understand your meaning) you can just give the color guide and its single break the same names as the fill guide and fill break:
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))
Upvotes: 5