前段时间项目中遇到过这种情况,在此通过两种方式实现了每根柱子颜色不同。
第一种方式:参照了http://blog.youkuaiyun.com/peterwanghao/article/details/7055967提供的方法。这里就不在献丑了,但是这种方式在使用的时候会遇到一种情况,就是柱状图的label不太好控制,和柱子对不上。如图一。
第二种方式:修改 org.jfree.data.general.DatasetUtilities中的createCategoryDataset方法,如图二。修改如下
@SuppressWarnings("rawtypes")
public static CategoryDataset createCategoryDataset(Comparable[] columnKeys, double[][] data) {
if (columnKeys == null) {
throw new IllegalArgumentException("Null 'columnKeys' argument.");
}
if (ArrayUtilities.hasDuplicateItems(columnKeys)) {
throw new IllegalArgumentException(
"Duplicate items in 'columnKeys'.");
}
int columnCount = 0;
for (int r = 0; r < data.length; ++r) {
columnCount = Math.max(columnCount, data[r].length);
}
if (columnKeys.length != columnCount) {
throw new IllegalArgumentException(
"The number of column keys does not match the number of columns in the data array.");
}
DefaultCategoryDataset result = new DefaultCategoryDataset();
for (int c = 0; c < data[0].length; ++c) {
Comparable columnKey = columnKeys[c];
result.addValue(new Double(data[0][c]), columnKey, columnKey);
}
return result;
}
图一:
图二: