绘制开始时间的实时图表

时间:2015-08-09 08:34:03

标签: java jfreechart

以下是基于@ trashgod' s example的关于实时绘图的代码:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.DynamicTimeSeriesCollection;
import org.jfree.data.time.Second;

/**
 * @see https://stackoverflow.com/a/21307289/230513
 */
public class DynamicTimeSeriesChart extends JPanel {

private static final long serialVersionUID = 5128935838291298041L;
private final DynamicTimeSeriesCollection dataset;
private final JFreeChart chart;

public DynamicTimeSeriesChart(final String title) {
    dataset = new DynamicTimeSeriesCollection(1, 1000, new Second());
    dataset.setTimeBase(new Second(0, 0, 0, 1, 1, 2014));
    dataset.addSeries(new float[1], 0, title);
    chart = ChartFactory.createTimeSeriesChart(
        title, "Time", title, dataset, true, true, false);
    final XYPlot plot = chart.getXYPlot();
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setFixedAutoRange(10000);
    axis.setDateFormatOverride(new SimpleDateFormat("ss.SS"));
    final ChartPanel chartPanel = new ChartPanel(chart);
    add(chartPanel);
}

public void update(float value) {
    float[] newData = new float[1];
    newData[0] = value;
    dataset.advanceTime();
    dataset.appendData(newData);
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            JFrame frame = new JFrame("testing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final DynamicTimeSeriesChart chart
                = new DynamicTimeSeriesChart("Alternating data");
            frame.add(chart);
            frame.pack();
            Timer timer = new Timer(1000, new ActionListener() {
                private boolean b;

                @Override
                public void actionPerformed(ActionEvent e) {
                    chart.update(b ? 1 : 0);
                    b = !b;
                }
            });
            timer.start();
            frame.setVisible(true);
        }
    });
}
}

运行Java之后,虽然new Seconds从0开始,但我还是不明白为什么图表会在40秒开始? 通过代码;无法在40秒内找到任何设置。

此外,如何向后滚动图表以查看以前的数据。

1 个答案:

答案 0 :(得分:3)

图表从用于构建传递给response = requests.get('http://my-slow-url') response.raw.chunked = True print(response.text) 的{​​{1}}的日期的午夜后16分40秒开始。这是在Second构造函数参数中指定的相同的1000个间隔,每个间隔长一秒。在时间设置为午夜的情况下,获得基于零的显示的一些可能的替代方案。

  1. setTimeBase()设为nMoments的倍数。

    nMoments
  2. 从名义基准日期减去60

    dataset = new DynamicTimeSeriesCollection(1, 960, new Second());
    dataset.setTimeBase(new Second(0, 0, 0, 1, 1, 2014));
    
  3. 任何一种方法都会产生相同的显示效果。

    image