Add legend to graph geom_line () in r

I am trying to add a legend to my ggplot, but failed. I tried the function scale_colour_manual(), but the legend is not displayed.

ggplot()+
geom_line(data=Summary,aes(y=Y1,x= X),colour="darkblue",size=1 )+
geom_line(data=Summary,aes(y=Y2,x= X),colour="red",size=1  )

My summary summary is as follows:

  X           Y1           Y2
139 1.465477e+16 7.173075e+15
277 1.044803e+16 9.275002e+15
415 1.059258e+16 8.562518e+15
553 1.033283e+16 8.268984e+15
691 9.548019e+15 1.022248e+16
830 1.008212e+16 8.641891e+15
968 9.822061e+15 9.315856e+15
1106 9.948143e+15 9.178694e+15
1244 1.013922e+16 8.825904e+15
1382 9.815094e+15 9.283662e+15

Please tell me how to build Y1, Y2 vs X on the same chart and add a legend on the side.

+12
source share
3 answers

ggplotrequired aesto make a legend, moving colourinside aes(...)will create the legend automatically. then we can adjust the legend labels with scale_color_discrete:

ggplot()+
    geom_line(data=Summary,aes(y=Y1,x= X,colour="darkblue"),size=1 )+
    geom_line(data=Summary,aes(y=Y2,x= X,colour="red"),size=1) +
    scale_color_discrete(name = "Y series", labels = c("Y2", "Y1"))

enter image description here

+21
source

, , . , , . scale_color_manual labs.

ggplot(data=Summary)+
  geom_line(mapping=aes(y=Y1,x= X,color="Y1"),size=1 ) +
  geom_line(mapping=aes(y=Y2,x= X,color="Y2"),size=1) +
  scale_color_manual(values = c(
    'Y1' = 'darkblue',
    'Y2' = 'red')) +
  labs(color = 'Y series')
+8

, geom:

ggplot2 ( -) , ( ). , , tidyr reshape2. , , , aes, .

:

library(tidyr)
library(ggplot2)

plot_data <- gather(data, variable, value, -x)

ggplot(plot_data, aes(x = x, y = value, color = variable)) +
  geom_line() +
  scale_color_manual(values = c("firebrick", "dodgerblue")) 

scale_color.

+3

Source: https://habr.com/ru/post/1662086/


All Articles