How to choose the right colour palette for plots with lots of variables? I am using R to generate several plots which will have 31 different variables grouped into 17 groups.
Unfortunately I found out that default's ggplot's colour palette with evenly spaced hues (which has worked great for me in the past) is not useful as it doesn't allow me to differenciate between variables, as their colours are too similar (see image below, which is still WIP and does not yet have all 31 variables). 

I can't use other nice colour palettes such as color brewer since I can only get 12 colours at most or colourlovers, but their palettes only work for five colours at most. 
I know that using ggplot I can customize my colour palette, but this question is about asking advice in how to pick the right colours: I would like them to be clearly distinguishable one from another and (if possible) to be displayed in a B/W publication.
As a final note I was considering that, since all 31 variables are grouped into 17 groups (some groups only contain one variable, whereas the one that has most of them contains  4), I may create 17 colour palettes, but still don't know how to proceed, as I do not have any knowledge on colour theory.
 A: Asking colors to differentiate 31 variables and still have them distinguishable in a gray-scale publication seems next to impossible in practice. (And don't forget how many individuals are color blind, for whom a detailed color display won't work well at all.)
Consider instead displaying your data in a different way. It seems that you are in part interested in comparing age distributions among different places. For that purpose, a lattice of age histograms, one for each place, might be more useful. An 8 x 4 lattice would allow you to show each of the 31 histograms individually, along with one that combines all the data. You could draw boxes around the histograms that belong to the same groups.
If you need to distinguish these places in other types of plots, you might be better off using plotting symbols that can be distinguished in gray scale. You can get 17 simple, distinguishable plotting symbols with squares, diamonds, up-triangles, down-triangles, and circles that are unfilled, gray-filled, and black-filled, along with "+" and "x" symbols.
When I'm reading I find it hard to keep track of large numbers of symbols even if they are in principle distinguishable and have good legends describing them. I suspect that many of your readers will have the same problem. Try to find ways to simplify your presentation as much as is reasonable.
