My application contains a line graph which can display 20 or more datasets at once, but typically it will be displaying less than 5. I'd like each dataset to have a unique color.
Currently I'm doing this:
setHsl(i * 255.0 / session->getNumDataSets(), 255, 128);
It works, but has the downside that two consecutive datasets will have very similar colors. I'd like it so that each color generated will be as contrasting as possible against all previous colors generated.
What is a better way to generate the colors?
Here is my second attempt:
double pos = 0;
if (wheel.size() == 0)
{
wheel.append(0.0);
wheel.append(1.0);
}
else
{
double gap = 0;
double hi = 0;
double lo = 0;
for (int i = 0; i < wheel.size() - 1; i++)
{
double g = wheel[i + 1] - wheel[i];
if (g > gap)
{
gap = g;
lo = wheel[i];
hi = wheel[i + 1];
}
}
pos = (hi - lo) / 2.0 + lo;
wheel.append(pos);
qSort(wheel);
}
QColor c;
c.setHsl(pos * 255.0, 255, 128);
return c.toRgb();
My idea is that the first color, is position 0 on the color wheel. Then for every following color, I go around the color wheel, looking for the biggest gap between colors, and once I've found it, I insert a new color into that gap. It seems to work better, but still isn't perfect, since once the gaps become small, consecutive colors become similar again.
I know you are asking for a way to computationally generate the colors for a graph, but you may want to consider designing a custom palette and looking up colors from a pre-stored table.
This has the advantage that you can craft a selection of colors that are more easy to distinguished for color blind users. You can use a tool like VisCheck to see how your graph would appear to color blind users.
If you may have more than 20 data sets I imagine it may be very hard to distinguish by color alone, but colors can be reused in combination with another differentiator, such as dashed lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With