组合条形图和折线图 JfreeChart。尝试用折线图制作 3 点平均值。这些值没有正确排列

Combined bar and line chart JfreeChart. Trying to make a 3 point average with the line chart. The values do not line up correctly

我的条形图有一个数据集,可以说:{1,2,3,4,5,6,7,8,9}。然后我有我的折线图,它假设是三点平均值,它是条形图在该索引处的值,以及之前的两个值,然后除以三。

对应的条形图值 1 和 2 应该不存在折线图,然后从位置 3 开始。我尝试使用 try and catch 块和 if 语句,以便它只在可能的情况下输入值,但是当我这样做时,它仍然从位置 1 开始绘制折线图,​​只是将其拉伸以适合图形。

我怎样才能使折线图从第 3 列开始,然后从那里继续?

这是我现在拥有的:

public class mockTest 扩展了 JFrame{

public mockTest()
{
    //Mock data
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();
    int[] times = new int[]{1,2,3,4,5,6,7,8,9};

    for ( int i = 0; i < times.length; i++ ){
        dataset.addValue(times[i], "Time", "Hour" + String.valueOf(i+1));;
        if(i>2)
        {
            dataset2.addValue((times[i] + times[i-1] + times[i-2])/3, "Time", "Hour" + String.valueOf(i+1));

        }

    }
    CategoryPlot plot = new CategoryPlot();

    //create the plot

    //add the first dataset, and render as bar values
    CategoryItemRenderer renderer = new BarRenderer();
    plot.setDataset(0,dataset);
    plot.setRenderer(0,renderer);  

    //add the second dataset, render as lines
    CategoryItemRenderer renderer2 = new LineAndShapeRenderer();
    plot.setDataset(1, dataset2);

    plot.setRenderer(1, renderer2);

    //set axis 
    CategoryAxis domainAxis = new CategoryAxis("Time");  
    NumberAxis rangeAxis = new NumberAxis("Value"); 

    plot.setDomainAxis(0,domainAxis);
    plot.setRangeAxis(rangeAxis);
    JFreeChart chart = new JFreeChart(plot);
    ChartPanel chartPanel = new ChartPanel( chart ); 

    this.setContentPane(chartPanel);
}   

** 弄清楚了,就在我放置 if(i<2) 语句的地方,添加一个 else 语句并将 null 作为值。

我最终使用了 try 和 catch 块,但是 if 和 else 也可以。在您不需要任何值的地方,只需将 null 作为值即可。

    for(int i=0;i<ints1.size();i++)
    {
        dataset.addValue(ints1.get(i), "Good Product", "Hour" + String.valueOf(i+1));
        dataset.addValue(ints2.get(i), "Bad Product", "Hour" + String.valueOf(i+1));
        try{
            dataset2.addValue((ints1.get(i) + ints1.get(i-1) + ints1.get(i-2))/3, "Time", "Hour" + String.valueOf(i+1));
            }
            catch(ArrayIndexOutOfBoundsException e)
            {
                dataset2.addValue(null, "Time", "Hour" + String.valueOf(i+1));
            }
    }