java如何GradientPaint JFreeChart AreaChart

时间:2013-11-12 12:48:15

标签: java swing jfreechart gradient

public static JFreeChart createAreaChart(double[] v1) {
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series1 = new XYSeries("First");
        for (int i=0;i<v1.length;i++){
            series1.add( i,v1[i]);
        }
        dataset.addSeries(series1);

        final JFreeChart chart = ChartFactory.createXYAreaChart(
            "XY Area Chart Demo",
            "Domain (X)", "Range (Y)",
            dataset,
            PlotOrientation.VERTICAL,
            true,  // legend
            true,  // tool tips
            false  // URLs
        );

        GradientPaint gp0 = new GradientPaint(
                0.0f, 0.0f, Color.red, 
                0.0f, 100.0f, Color.blue
            );

        chart.setBackgroundPaint(Color.white);

        final XYPlot plot = chart.getXYPlot();
        plot.getRenderer().setSeriesPaint(0, gp0);
        //plot.setOutlinePaint(Color.black);
        plot.setBackgroundPaint(Color.lightGray);
        plot.setForegroundAlpha(0.99f);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);

        final ValueAxis domainAxis = plot.getDomainAxis();
        domainAxis.setTickMarkPaint(Color.black);
        domainAxis.setLowerMargin(0.0);
        domainAxis.setUpperMargin(0.0);

        final ValueAxis rangeAxis = plot.getRangeAxis();
        rangeAxis.setTickMarkPaint(Color.black);
        rangeAxis.setAutoRange(false);
        rangeAxis.setRange(-5.0, 5.0);

        return chart;

    }

我想要下面这样的东西。当我们越过零线时,渐变填充会缓慢切换颜色。

我不明白我应该放什么:

    GradientPaint gp0 = new GradientPaint(
            0.0f, 0.0f, Color.red, 
            0.0f, 100.0f, Color.blue
        );

enter image description here

2 个答案:

答案 0 :(得分:0)

最好的方法是拥有3个形状。一个为黄线。另一个是绿色渐变,第三个是红色渐变。

然后你独立地绘制最后两个形状。

答案 1 :(得分:0)

我相信一个更好的起点是XYDifferenceRenderer让一个系列保持零,这样当第二个seires通过它时颜色会改变。看看JFreeChart中的DifferenceChartDemo1。将两个不同的Color GradientPaints放在渲染器的构造函数中。

以下是渲染器的API链接: http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/renderer/xy/XYDifferenceRenderer.html