有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JFreechart Boxplot在为方框着色时更改方框大小

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

enter image description here

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

enter image description here

我如何才能得到第二个图形的颜色,但与第一个盒子大小


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);
    }
}

共 (1) 个答案

  1. # 1 楼答案

    不同之处在于,第一张图片有一个系列,而第二张图片有五个系列。不要添加很多系列,而是添加一个包含五个项目的系列,比如你的头像。您可以使用一个自定义的BoxAndWhiskerRenderer来覆盖^{}以获得不同的颜色,就像它们为XYLineAndShapeRenderer显示here

    编辑:要获得匹配的图例,需要一个新的^{}比如this