0

I am trying to plot several different columns against the same x using ggplot. I have produced a plot with the lines as required, but can't work out how to add a legend linking each column title to the line colour shown in ggplot for that line.

My plotting code is:

#Plots Ceff, C2d and C3d vs log(freq)

ggplot(plotting, 
       mapping = aes(x = lfreq,y = Ceff))+
  geom_line()+
  geom_line(mapping = aes(x = lfreq ,y = C2D ), color = "green", show.legend = TRUE)+
  geom_line(mapping = aes(x = lfreq, y = C3D), color = "blue")+
  geom_line(mapping = aes(x = lfreq, y = Clim), color = "red")+
  geom_line(mapping = aes(x = lfreq, y = K), color = "purple")+
  ylim(c(0.00001, 0.0005))+
  xlim(c(-1, 5))+
  xlab("log(W)")+
  ylab("C (F/cm2)")

I have tried to add:

scale_shape_discrete(name = "Capacitance",
                       breaks = c("Ceff", "C2D", "C3D", "Clim", "K"),
                       labels = c("Ceff", "C2D", "C3D", "Clim", "K"))

to my ggplot, and also add show.legend = "True" to each geom_line() but neither has had any effect. Apologies - I can see there are lot's of answers about this topic but I can't work out how to apply this to my situation.

stefan
  • 90,330
  • 6
  • 25
  • 51
Kieran
  • 3
  • 2
  • please share your data or toy data so others can help. I would recommend transposing the data from wide to long and then trying to plot, it will clean up the code a bit – Mike Aug 17 '23 at 15:48
  • 1
    If you want a legend you have to map on aesthetics, i.e move `color=` inside of `aes()`. – stefan Aug 17 '23 at 15:50
  • Hi both, thank you! Mike's allowed the easier solution (fewer changes to my messy script..) but thanks for the help! – Kieran Aug 17 '23 at 16:17

0 Answers0