Question

How can I make a ggplot that has two labels/legends?

Example data dput():

structure(list(Percentage = c(0, 25, 50, 75, 100, 0, 25, 50, 75, 100), Data = c("group1", "group1", "group1", "group1", "group1", "group2", "group2", "group2", "group2", "group2"), accuracy_G = c(18.35, 54.53, 68.48, 88.65, 99.96, 18.35, 76.08, 81.63, 88.03, 99.96 ), accuracy_1 = c(52.751572327044, 61.5566037735849, 65.8411949685535, 73.8011006289308, 80.6112421383648, 52.751572327044, 64.7209119496855, 67.3054245283019, 70.5090408805032, 80.6112421383648), accuracy_2 = c(52.8498427672956, 61.1930031446541, 66.0966981132076, 73.8404088050314, 80.3360849056604, 52.8498427672956, 64.5538522012579, 67.1678459119497, 70.9217767295598, 80.3360849056604)), .Names = c("Percentage", "Data", "accuracy_G", "accuracy_1", "accuracy_2"), row.names = c(2L, 4L, 6L, 8L, 10L, 12L, 14L, 16L, 18L, 20L), class = "data.frame")

require(ggplot2)
require(reshape2)
data.melt <- melt(data, id.vars=c("Percentage","Data")) #For plotting with ggplot

Now I can plot part of the figure by subsetting:

data.melt_sub <- subset(data.melt,Data == "group1")
ggplot( data.melt_sub ,aes(x = Percentage,y = value,colour=variable)) + geom_line() 

However, I would like to have two labels on the right, one for 'group1' and one for 'group2' (each creating 3 lines). For the colours of the lines i would like to use the palette = "Paired", from the brewer. These could be called by hand with, but including something like scale_fill_brewer(pallete = "Paired") would be better:

require(RColorBrewer)
colours <- brewer.pal(12,"Paired")
Was it helpful?

Solution

Use your full melted data frame and then for color= inside aes() provide interaction between Data and variable. Then with scale_color_manual() change line colors and labels inside the legend.

ggplot( data.melt ,aes(x = Percentage,y = value,colour=interaction(Data,variable))) + 
  geom_line() + scale_color_manual(values=brewer.pal(6,"Paired"),
                                   labels=rep(c("Group1","Group2"),times=3))

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top