2015-04-07 79 views
1

我正在使用JFreeChart使用折線圖繪製兩個數據系列(XYSeries)。 其中一個數據系列的y值通常遠高於我的第二個數據系列的y值(假設第一個系列的y值在數百萬的數量級上,而第二個系列具有幾百個數量級的y值)。在我的第一個數據集中存在高值會導致圖的範圍變得這樣,以至於我的第二個數據集的y值不再被理解。使用JFreeChart爲兩個系列設置不同的y軸

將第二個y軸添加到圖中,以便我的數據序列都使用它們自己的y軸,將解決此問題。有誰知道如何與JFreeChart做到這一點?

當前的完整性代碼:

XYSeriesCollection dataset = new XYSeriesCollection(); 
XYSeries series1 = new XYSeries("series1"); 
XYSeries series2 = new XYSeries("series2"); 

// Here is my code to fill series1 and series2 with data  

dataset.addSeries(series1); 
dataset.addSeries(series2); 

JFreeChart chart = ChartFactory.createXYLineChart(
    "title", "x-axis title", "y-axis title", dataset, PlotOrientation.VERTICAL, true, true, false 
); 
chart.getXYPlot().setRenderer(new XYSplineRenderer()); 

回答

6

您可以手動創建的JFreeChart對象,而不是使用ChartFactory的的。首先生成數據集和繪圖,將每個數據集設置爲一個索引。然後您可以使用必要的軸和渲染器自定義繪圖。下面是一個使用具有兩個數據集(每個數據集都具有不同的大小y值)的虛擬數據的示例:

//create the series - add some dummy data 
    XYSeries series1 = new XYSeries("series1"); 
    XYSeries series2 = new XYSeries("series2"); 
    series1.add(1000, 1000); 
    series1.add(1150, 1150); 
    series1.add(1250, 1250); 

    series2.add(1000, 111250); 
    series2.add(1150, 211250); 
    series2.add(1250, 311250); 

    //create the datasets 
    XYSeriesCollection dataset1 = new XYSeriesCollection(); 
    XYSeriesCollection dataset2 = new XYSeriesCollection(); 
    dataset1.addSeries(series1); 
    dataset2.addSeries(series2); 

    //construct the plot 
    XYPlot plot = new XYPlot(); 
    plot.setDataset(0, dataset1); 
    plot.setDataset(1, dataset2); 

    //customize the plot with renderers and axis 
    plot.setRenderer(0, new XYSplineRenderer());//use default fill paint for first series 
    XYSplineRenderer splinerenderer = new XYSplineRenderer(); 
    splinerenderer.setSeriesFillPaint(0, Color.BLUE); 
    plot.setRenderer(1, splinerenderer); 
    plot.setRangeAxis(0, new NumberAxis("Series 1")); 
    plot.setRangeAxis(1, new NumberAxis("Series 2")); 
    plot.setDomainAxis(new NumberAxis("X Axis")); 

    //Map the data to the appropriate axis 
    plot.mapDatasetToRangeAxis(0, 0); 
    plot.mapDatasetToRangeAxis(1, 1); 

    //generate the chart 
    JFreeChart chart = new JFreeChart("MyPlot", getFont(), plot, true); 
    chart.setBackgroundPaint(Color.WHITE); 
    JPanel chartPanel = new ChartPanel(chart);