Dienstag, 15. Juli 2014

Custom chart color calculation in java (eg. for google charts, jfreechart, etc.)

I often had the problem to find custom colors for charts (e.g. pie charts) to match the website CI. I searched the web and found a way to generate any number of colors based on a single color by modifing the hue value of the color.

The used java code can be found below. It uses a HSLColor class which can be found here.

package customcolors;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

public class CustomColors {

/**
* @param args
*/
public static void main(String[] args) {

int count = 24;

List<Color> colors = new ArrayList<Color>();

Color baseColor = new Color(0x798e30);
HSLColor hslColor = new HSLColor(baseColor);

float baseHue = hslColor.getHue();

colors.add(baseColor);

float step = (360 / count);

for (int i = 1; i < count; ++i) {

float nextHue = (float) (baseHue + step * i) % 360;

HSLColor nextColor = new HSLColor(nextHue,
hslColor.getSaturation(), hslColor.getLuminance());

colors.add(nextColor.getRGB());
}

StringBuffer colorBuffer = new StringBuffer();

for (Color tempColor : colors) {

String hex = Integer.toHexString(tempColor.getRGB()).substring(2);
colorBuffer.append(hex);
colorBuffer.append(",");
}

String colorString = colorBuffer.toString();
colorString = colorString.substring(0, colorString.length() - 1);

StringBuffer dataBuffer = new StringBuffer();

for (int i = 1; i < count; ++i) {

dataBuffer.append("10");
dataBuffer.append(",");
}

String dataString = dataBuffer.toString();
dataString = dataString.substring(0, dataString.length() - 1);

System.out.print("http://chart.apis.google.com/chart?chs=400x400&cht=p&chco=" + colorString + "&chd=t:" + dataString);

}

}

Following chart colors are generated: