如何将比例尺或轴添加到散点图?

时间:2016-03-29 08:22:58

标签: java swing jfreechart axis scatter-plot

我写了一些代码,将坐标绘制到绘图区域(JPanel)。这是我的代码类:

class POSCanvas extends JPanel {
    private XYSeries pnts = new XYSeries("Position");

    public POSCanvas() {
        final ChartPanel chartPanel = createDemoPanel();
        this.add(chartPanel, BorderLayout.CENTER);
    }

    private void update(double xnew, double ynew) {
        pnts.add(new XYDataItem(xnew, ynew));
    }

    private ChartPanel createDemoPanel() {
        JFreeChart jfreechart = ChartFactory.createScatterPlot(
            "", "X", "Y", createSampleData(),
            PlotOrientation.VERTICAL, true, true, false);
        XYPlot xyPlot = (XYPlot) jfreechart.getPlot();
        XYItemRenderer renderer = xyPlot.getRenderer();
        NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis();
        int minX = (int)pnts.getMinX(); int maxX = (int)pnts.getMaxX();
        if (minX < maxX){domain.setRange(minX, maxX);}
        domain.setTickUnit(new NumberTickUnit(1));
        NumberAxis range = (NumberAxis) xyPlot.getRangeAxis();
        range.setTickUnit(new NumberTickUnit(1));
        return new ChartPanel(jfreechart){
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(640, 480);
            }
        };
    }

    private XYDataset createSampleData() {
        XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
        xySeriesCollection.addSeries(pnts);
        return xySeriesCollection;
    }
}

问题是我似乎无法添加X轴的范围。这是输出: enter image description here

我正在使用domain.setRange()方法,但它不起作用。知道怎么解决吗?任何帮助,将不胜感激;谢谢。

1 个答案:

答案 0 :(得分:2)

尝试ChartFactory.createScatterPlot(),其中“使用XYPlot实例作为图表,域轴为NumberAxi,范围轴为NumberAxisXYLineAndShapeRenderer作为渲染器。“显示了几个完整的示例here,工厂的source包含在发行版中。

image