Search code examples
rggplot2aesthetics

Change color and add legend in ggplot


I'm trying to plot some data ("DAPC2") with two variables linked to coordinates in ggplot2. The data looks like this:

         LD1        LD2      Locality   Ecoregion
CA2   0.9524254  -15.906715  Caldera    Central_Chile
CO4   11.4640606  3.644242   Cocholgue  Araucanian
HU2  -17.3216357  10.577911  Huinay     Chiloense
HU4  -17.9015095  10.813084  Huinay     Chiloense
LH1   2.5713149  -17.984544  Herradura  Central_Chile

And my code so far is something like this:

myPlot <- ggplot(DAPC2, aes(x=DAPC2$LD1, y=DAPC2$LD2))
myPlot + theme_bw() + theme(panel.border=element_blank(), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), axis.line=element_line(colour="black")) + geom_point(alpha=0.3, col=as.integer(DAPC2$popnames.Locality), pch=as.integer(DAPC2$popnames.Ecoregion)+14, cex=6)

On one hand, I 'm trying to change the color palette, however I could not do it given the integer vector. Also, I'm trying to include a legend that show both variables (i.e. Locality and Ecoregion). Any advice?


Solution

  • To add colour/shapes to points in ggplot, you want to add colour and shape aesthetics.

    Try

    ggplot(DAPC2, aes(x=DAPC2$LD1, y=DAPC2$LD2, colour=Locality, shaoe=Ecoregion))

    and remove all instances if Ecoregion and Locality from the rest of your code. This will also add a legend for both colour and shape.