Thursday, June 14, 2012

Mixed Shapes/Colors in R's ggplot

R is easier to learn than Dwarf Fortress, and just as awesome, although it is for statistical analysis and visualization, not beer-swilling dwarf sim fans. But I had a little problem when trying to get both different shapes and colors, at the same time, in a scatterplot in ggplot.

(Ok I went back to edit this and Google destroyed it, sometimes blogger is ok with greater- and less-than, other times, it will destroy the entire post.) But, what was going on? I knew you could do both the color and the shape simultaneously, as there is an example of both shape and color being user-set in the ggplot2 book by ggplot's creator, Hadley Wickham, but there was no code sample (page 112, figure 6.14).

Turns out you have to "activate" the attributes you want to set manually!

I had a hard time finding and understanding the extensive and somewhat diverse help sources, so thought I'd put this up.

Here is the final working code -- I had to go back into my files to get it. Note I'll use the equals sign here (so the post doesn't blow up again).

my_graph = ggplot(my_csv_data) + 
    geom_point(aes(my_x_value, my_y_value, color = Desc, shape = Desc)) +
    scale_colour_manual(name = "Legend Name", values = c("This" = "black", "That" = "red", "Also" = "grey33")) +
    scale_shape_manual(name = "Legend Name", values = c(1, 2, 5)) 

The comment I have after that code:
You need BOTH color = and shape = in the aes call or else the later scale calls won't work for whichever you don't have!