JFreeChart with truncated data points

前端 未结 2 1607
野的像风
野的像风 2021-01-27 07:33

I have created a JFreeChart with the code below, but the Y-Axis marks are truncated. How should I display the chart even though the data points are overlapped in the Y-Axis? Bas

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-27 08:34

    I have managed to sort this out, by reading the data points, finding the maximum number, then inserting maximum under xyplot setRange() method.

    You shouldn't have to do so. In the excerpt below, why are you getting the domain axis, replacing it with reference to the the range axis, and then altering the range axis? Did you mean to change the domain axis, instead? See this related example.

    domainAxis = (NumberAxis) plot.getDomainAxis();
    domainAxis = (NumberAxis) plot.getRangeAxis();
    domainAxis.setAutoRangeIncludesZero(false);
    

    Addendum: A minimal sscce showing auto-range of random data.

    image

    import java.awt.EventQueue;
    import java.util.Random;
    import javax.swing.JFrame;
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartPanel;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.plot.XYPlot;
    import org.jfree.data.time.Day;
    import org.jfree.data.time.Hour;
    import org.jfree.data.time.TimeSeries;
    import org.jfree.data.time.TimeSeriesCollection;
    
    /** @see https://stackoverflow.com/a/14198851/230513 */
    public class Test {
    
        private static final int N = 10;
        private static final Random random = new Random();
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new Test().display();
                }
            });
        }
    
        private void display() {
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new ChartPanel(buildChart(createDataset(), "Title")));
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    
        private static TimeSeriesCollection createDataset() {
    
            final TimeSeries series = new TimeSeries("Data");
            Hour current = new Hour(0, new Day());
            for (int i = 0; i < N; i++) {
                series.add(current, random.nextGaussian());
                current = (Hour) current.next();
            }
            return new TimeSeriesCollection(series);
        }
    
        private static JFreeChart buildChart(
            TimeSeriesCollection dataset, String title) {
            JFreeChart chart = ChartFactory.createTimeSeriesChart(
                title, "Hour", "Count", dataset, true, true, false);
            XYPlot plot = chart.getXYPlot();
            plot.setDomainCrosshairVisible(true);
            plot.setRangeCrosshairVisible(true);
            return chart;
        }
    }
    

提交回复
热议问题