schande
schande

Reputation: 658

Adding a legend with ggplot failed

I try to add a legend to my chart using scale_color_manual but when I use it as seen below, it just simply is not there. To color the lines gradiently (not sure if it is the right word) I use color =sapply(1/16, hsv, 0.7, 0.7). After fixing the not appearing of the legend, I will change the colors in the legend to the ones they actually have in the graph. I tried adding show_guide=TRUE in the aesthetics of every stat_summary but it says that it is an unknown aesthetic.

colnames(my_dataframe) <- c("Group","a1","a2")

(ggplot(data=my_dataframe, aes(x=my_dataframe$Group)) 
  + stat_summary(fun.y = mean, geom = "line", color =sapply(1/16, hsv, 0.7, 0.7), aes(y=my_dataframe$a1)) 
  + stat_summary(fun.y = mean, geom = "line", color =sapply(2/16, hsv, 0.7, 0.7), aes(y=my_dataframe$a2))  
  + xlab("X-Axis") 
  + ylab("Y-Axis")
  + scale_colour_manual(name = 'Trials', 
                        values =c('black'='black','red'='red'), labels = c('1','2'))
  )

My dataframe before changing the column names looks like this:

myTable1 <- " 
       5    3  8
       5    3  7
       4.9  2  6   
       4.9  3  5
       4.9  1  4
       2.0  2  5"
Data <- read.table(text=myTable1, header = FALSE)

Upvotes: 1

Views: 93

Answers (1)

PKumar
PKumar

Reputation: 11128

Are you trying to this, you have to melt the data first in the long form to get the desired result, I am using reshape2 package here , you can also use gather from tidyverse here :

library(reshape2)
dat <- read.table(text=myTable1, header = FALSE)
colnames(dat) <- c("Group","a1","a2")

melt_dat <- melt(dat, "Group") # You have to melt your data into long form so that you can get the legend 

ggplot(data=melt_dat, aes(x=Group,y=value, color=variable)) +
  stat_summary(fun.y = mean, geom = "line") +
  xlab("X-Axis") + 
  ylab("Y-Axis") 

Output:

enter image description here

Upvotes: 2

Related Questions