Search code examples
rggplot2labellegend-properties

Adding Custom Legend to 2 Data sets in ggplot2


I am trying to simply add a legend to my Nyquist plot where I am plotting 2 sets of data: 1 is an experimental set (~600 points), and 2 is a data frame calculated using a transfer function (~1000 points)

I need to plot both and label them. Currently I have them both plotted okay but when i try to add the label using scale_colour_manual no label appears. Also a way to move this label around would be appreciated!! Code Below.

    pdf("nyq_2elc.pdf")

  nq2 <- ggplot() + geom_point(data = treat, aes(treat$V1,treat$V2), color = "red") +
    geom_point(data = circuit, aes(circuit$realTF,circuit$V2), color = "blue") +
    xlab("Real Z") + ylab("-Imaginary Z") + 
    scale_colour_manual(name = 'hell0', 
                       values =c('red'='red','blue'='blue'), labels = c('Treatment','EQ')) +
    ggtitle("Nyquist Plot and Equivilent Circuit for 2 Electrode Treatment Setup at 0 Minutes") +
    xlim(0,700) + ylim(0,700) 


print(nq2)
dev.off()

Solution

  • Ggplot works best with long dataframes, so I would combine the datasets like this:

    treat$Cat <- "treat"
    circuit$Cat <- "circuit"
    CombData <- data.frame(rbind(treat, circuit))
    
    ggplot(CombData, aes(x=V1, y=V2, col=Cat))+geom_point()
    

    This should give you the legend you want.

    You probably have to change the names/order of the columns of dataframes treat and circuit so they can be combined, but it's hard to tell because you're not giving us a reproducible example.