Get legend from different data frames

Hi, this is my first post. I've been looking for answers here and there but i can´t solve this:

I have some data that is plotted with ggplot as dots. Then i created a data frame that contains the values of a line that i need to plot in the previous plot. It works well with my code but i cant see the name of the line in the legend box. Thanks in advance.

t <- -40:10
z <- (8*t)+10
df3 = data.frame(t, z)
names(df3) <- c("t", "z")
df3$lin <- c("lin")

sp3<-ggplot(Datos, aes(x=O18, y=H2, color=Lugar)) +
  geom_point(shape = 21, size=1)+xlim(-50, 20)+ylim(-350, 100)+geom_line(data=df3, aes(x=t, y = z), color= "red")
sp3+labs(x = expression(paste(delta^{18}, "O (\u2030)"[VSMOW])), y = expression(paste(delta^{2}, "H (\u2030)"[VSMOW])))+
  theme_bw()+
  scale_color_brewer(palette = "Set1")+
  theme(legend.position = c(0.8, 0.2), legend.title = element_blank(),panel.border = element_rect(colour = "black", fill=NA), legend.box.background = element_rect(colour = "black"))+
  guides(color = guide_legend(override.aes = list(size = 3)))

Hi!

To help us help you, could you please turn this into a proper reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

1 Like

I think the problem is that for geom_line() you defined color not inside of aes(), hence there is no mapping for the line in legend. If you add color = lin it probably would work.


t <- -40:10
z <- (8*t)+10
df3 = data.frame(t, z)
names(df3) <- c("t", "z")
df3$lin <- c("lin")

sp3<-ggplot(Datos, aes(x=O18, y=H2, color=Lugar)) +
  geom_point(shape = 21, size=1)+xlim(-50, 20)+ylim(-350, 100)+geom_line(data=df3, aes(x=t, y = z, color = lin))
sp3+labs(x = expression(paste(delta^{18}, "O (\u2030)"[VSMOW])), y = expression(paste(delta^{2}, "H (\u2030)"[VSMOW])))+
  theme_bw()+
  scale_color_brewer(palette = "Set1")+
  theme(legend.position = c(0.8, 0.2), legend.title = element_blank(),panel.border = element_rect(colour = "black", fill=NA), legend.box.background = element_rect(colour = "black"))+
  guides(color = guide_legend(override.aes = list(size = 3)))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.