Prabhu
Prabhu

Reputation: 87

Adding legends and data labels to the multiple line graph

I have a data frame like this

x<-seq(1,4,1) 
y1<-round(31,59,123,189)
y2<-c(30,55,180,200)
df <- data.frame(x,y1,y2)

I want to plot a multiple line plot with added legends and data labels in the grph.Currently I am usimg following lines of codes

ggplot(df, aes(x)) +                   
  geom_line(aes(y=y1,), colour="red") +  
  geom_line(aes(y=y2), colour="green")+
  xlab("X")+ylab("Y")

I am not getting the perfect output with added legends and data labels to the graph using any of the methods suggested.Can someone help me?

Upvotes: 0

Views: 847

Answers (1)

MKR
MKR

Reputation: 1700

You should first transform your data frame to the "long" format and then tell ggplot which column denotes the groupings.

library(tidyverse)
x<-seq(1,4,1) 
y1<-c(31,59,123,189)
y2<-c(30,55,180,200)
df <- data.frame(x,y1,y2)
df
#>   x  y1  y2
#> 1 1  31  30
#> 2 2  59  55
#> 3 3 123 180
#> 4 4 189 200
#>   x  y1  y2
#> 1 1  31  30
#> 2 2  59  55
#> 3 3 123 180
#> 4 4 189 200

#transform your dataframe

df <- df %>% pivot_longer(-x, names_to = "factor", values_to = "value")

ggplot(df, aes(x =x, y=value, group=factor, label = value)) +
  geom_line(aes(colour=factor)) +
  geom_text(hjust = 0, nudge_x = -0.2, aes(colour = factor)) 

Created on 2020-07-28 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions