JFreechart Boxplot 在为框着色时改变框的大小

JFreechart Boxplot changing size of boxes when coloring the boxes

我正在使用 JFreeChart 制作箱线图(代码在底部)。当我不为每个框添加颜色时,它们会被绘制得更宽并且正确居中(如我所愿):

然而,当我用 x 轴标签给它们上色时,它们变小并且不再正确居中:

如何获得第二个图形的颜色,但使用第一个图形的框大小?


package test;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.BoxAndWhiskerToolTipGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BoxAndWhiskerRenderer;
import org.jfree.data.statistics.DefaultBoxAndWhiskerCategoryDataset;

public class test {
    public static void main(String[] args) throws Exception {
    DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

    // example data
    HashMap<String, ArrayList<Double>> test = new HashMap<String, ArrayList<Double>>();
    test.put("A",new ArrayList<Double>(Arrays.asList(0.8, 1.4, 0.8, 1.9, 1.2)));
    test.put("B",new ArrayList<Double>(Arrays.asList(0.8, 1.4, 0.8, 1.9, 1.2)));
    test.put("C",new ArrayList<Double>(Arrays.asList(0.8, 1.4, 0.8, 1.9, 1.2)));
    test.put("D",new ArrayList<Double>(Arrays.asList(0.8, 1.4, 0.8, 1.9, 1.2)));
    test.put("E",new ArrayList<Double>(Arrays.asList(0.8, 1.4, 0.8, 1.9, 1.2)));
    for (String k : test.keySet()){
        /* change to 
         *     String xAxisLabel = "";
         * to get wide plot
         */
        String xAxisLabel = k;
        dataset.add(test.get(k), xAxisLabel, k);// + beta of interactionterm");
    }
    final CategoryAxis xAxis = new CategoryAxis("Example x-axis");
    final NumberAxis yAxis = new NumberAxis("Example y-axis");
    yAxis.setAutoRangeIncludesZero(false);
    final BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
    renderer.setFillBox(true);
    renderer.setSeriesToolTipGenerator(1, new BoxAndWhiskerToolTipGenerator());
    renderer.setMeanVisible(false);
    final CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis, renderer);

    final JFreeChart chart = new JFreeChart(
            "Example",
            plot
            );
    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(3000,1800));
    ChartUtilities.saveChartAsPNG(new File("test.png"), chart, 1000, 600);
    }
}

区别在于你的第一张图片有一个系列,而你的第二张图片有五个系列。不要添加很多系列,而是添加一个包含五个项目的系列,就像您的顶部图片一样。您可以使用覆盖 getItemPaint() to get different colors like they show here 的自定义 BoxAndWhiskerRenderer for XYLineAndShapeRenderer.

编辑:要获得匹配的图例,您需要一个新的 DrawingSupplier like this