Example usage for org.jfree.chart ChartFactory createTimeSeriesChart

List of usage examples for org.jfree.chart ChartFactory createTimeSeriesChart

Introduction

In this page you can find the example usage for org.jfree.chart ChartFactory createTimeSeriesChart.

Prototype

public static JFreeChart createTimeSeriesChart(String title, String timeAxisLabel, String valueAxisLabel,
        XYDataset dataset, boolean legend, boolean tooltips, boolean urls) 

Source Link

Document

Creates and returns a time series chart.

Usage

From source file:net.commerce.zocalo.freechart.ChartGenerator.java

private static JFreeChart priceVolumeHistoryChart(String title, TimePeriodValuesCollection prices,
        TimePeriodValuesCollection volumes, boolean scalePrices) {
    JFreeChart chart = ChartFactory.createTimeSeriesChart(title, null, "Price", prices, false, false, false);
    XYPlot plot = chart.getXYPlot();//from   w ww  .j a v  a 2  s . co m
    if (scalePrices) {
        setBoundsForPrice(chart);
    } else {
        setBoundsForPercent(chart);
    }

    NumberAxis rangeAxis2 = new NumberAxis("Volume");
    rangeAxis2.setUpperMargin(2);
    plot.setRangeAxis(1, rangeAxis2);
    plot.setDataset(1, volumes);
    plot.mapDatasetToRangeAxis(1, 1);
    XYBarRenderer renderer2 = new XYBarRenderer(0.2);
    plot.setRenderer(1, renderer2);
    return chart;
}

From source file:nu.nethome.home.items.web.GraphServlet.java

/**
* This is the main enterence point of the class. This is called when a http request is
* routed to this servlet./*  w  w w .  ja  v a 2 s . co  m*/
*/
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ServletOutputStream p = res.getOutputStream();
    Date startTime = null;
    Date stopTime = null;

    // Analyse arguments
    String fileName = req.getParameter("file");
    if (fileName != null)
        fileName = getFullFileName(fromURL(fileName));
    String startTimeString = req.getParameter("start");
    String stopTimeString = req.getParameter("stop");
    try {
        if (startTimeString != null) {
            startTime = m_Format.parse(startTimeString);
        }
        if (stopTimeString != null) {
            stopTime = m_Format.parse(stopTimeString);
        }
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    String look = req.getParameter("look");
    if (look == null)
        look = "";

    TimeSeries timeSeries = new TimeSeries("Data", Minute.class);

    // Calculate time window
    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Date startOfDay = cal.getTime();
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    Date startOfWeek = cal.getTime();
    cal.set(Calendar.DAY_OF_MONTH, 1);
    Date startOfMonth = cal.getTime();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    Date startOfYear = cal.getTime();

    // if (startTime == null) startTime = startOfWeek;
    if (stopTime == null)
        stopTime = currentTime;
    if (startTime == null)
        startTime = new Date(stopTime.getTime() - 1000L * 60L * 60L * 24L * 2L);

    try {
        // Open the data file
        File logFile = new File(fileName);
        Scanner fileScanner = new Scanner(logFile);
        Long startTimeMs = startTime.getTime();
        Long month = 1000L * 60L * 60L * 24L * 30L;
        boolean doOptimize = true;
        boolean justOptimized = false;
        try {
            while (fileScanner.hasNext()) {
                try {
                    // Get next log entry
                    String line = fileScanner.nextLine();
                    if (line.length() > 21) {
                        // Adapt the time format
                        String minuteTime = line.substring(0, 16).replace('.', '-');
                        // Parse the time stamp
                        Minute min = Minute.parseMinute(minuteTime);

                        // Ok, this is an ugly optimization. If the current time position in the file
                        // is more than a month (30 days) ahead of the start of the time window, we
                        // quick read two weeks worth of data, assuming that there is 4 samples per hour.
                        // This may lead to scanning past start of window if there are holes in the data
                        // series.
                        if (doOptimize && ((startTimeMs - min.getFirstMillisecond()) > month)) {
                            for (int i = 0; (i < (24 * 4 * 14)) && fileScanner.hasNext(); i++) {
                                fileScanner.nextLine();
                            }
                            justOptimized = true;
                            continue;
                        }
                        // Detect if we have scanned past the window start position just after an optimization scan.
                        // If this is the case it may be because of the optimization. In that case we have to switch 
                        // optimization off and start over.
                        if ((min.getFirstMillisecond() > startTimeMs) && doOptimize && justOptimized) {
                            logFile = new File(fileName);
                            fileScanner = new Scanner(logFile);
                            doOptimize = false;
                            continue;
                        }
                        justOptimized = false;
                        // Check if value is within time window
                        if ((min.getFirstMillisecond() > startTimeMs)
                                && (min.getFirstMillisecond() < stopTime.getTime())) {
                            // Parse the value
                            double value = Double.parseDouble((line.substring(20)).replace(',', '.'));
                            // Add the entry
                            timeSeries.add(min, value);
                            doOptimize = false;
                        }
                    }
                } catch (SeriesException se) {
                    // Bad entry, for example due to duplicates at daylight saving time switch
                } catch (NumberFormatException nfe) {
                    // Bad number format in a line, try to continue
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            fileScanner.close();
        }
    } catch (FileNotFoundException f) {
        System.out.println(f.toString());
    }

    // Create a collection for plotting
    TimeSeriesCollection data = new TimeSeriesCollection();
    data.addSeries(timeSeries);

    JFreeChart chart;

    int xSize = 750;
    int ySize = 450;
    // Customize colors and look of the Graph.
    if (look.equals("mobtemp")) {
        // Look for the mobile GUI
        chart = ChartFactory.createTimeSeriesChart(null, null, null, data, false, false, false);
        XYPlot plot = chart.getXYPlot();
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        xSize = 175;
        ySize = 180;
    } else {
        // Create a Chart with time range as heading
        SimpleDateFormat localFormat = new SimpleDateFormat();
        String heading = localFormat.format(startTime) + " - " + localFormat.format(stopTime);
        chart = ChartFactory.createTimeSeriesChart(heading, null, null, data, false, false, false);

        Paint background = new Color(0x9D8140);
        chart.setBackgroundPaint(background);
        TextTitle title = chart.getTitle(); // fix title
        Font titleFont = title.getFont();
        titleFont = titleFont.deriveFont(Font.PLAIN, (float) 14.0);
        title.setFont(titleFont);
        title.setPaint(Color.darkGray);
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(background);
        plot.setDomainGridlinePaint(Color.darkGray);
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        plot.setRangeGridlinePaint(Color.darkGray);
        XYItemRenderer renderer = plot.getRenderer(0);
        renderer.setSeriesPaint(0, Color.darkGray);
        xSize = 750;
        ySize = 450;
    }

    try {
        res.setContentType("image/png");
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "no-cache");
        res.setStatus(HttpServletResponse.SC_OK);
        ChartUtilities.writeChartAsPNG(p, chart, xSize, ySize);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

    p.flush();
    p.close();
    return;
}

From source file:org.zaproxy.zap.extension.ascan.ScanProgressDialog.java

private JFreeChart createChart(final XYDataset dataset) {
    JFreeChart result = ChartFactory.createTimeSeriesChart(null, // No title - it just takes up space 
            Constant.messages.getString("ascan.progress.chart.time"),
            Constant.messages.getString("ascan.progress.chart.responses"), dataset, true, true, false);
    XYPlot plot = result.getXYPlot();/*from   w w  w  . j  a  v  a  2  s. c  o  m*/
    ValueAxis daxis = plot.getDomainAxis();
    daxis.setAutoRange(true);
    daxis.setAutoRangeMinimumSize(60000.0);

    plot.getRangeAxis().setAutoRangeMinimumSize(20);

    return result;
}

From source file:test.integ.be.fedict.performance.util.PerformanceResultDialog.java

private JFreeChart getPerformanceChart(int intervalSize, List<PerformanceData> performance,
        int expectedRevoked) {
    TimeSeries series = new TimeSeries("Success");
    TimeSeries revokedSeries = new TimeSeries("Revoked");
    TimeSeries failureSeries = new TimeSeries("Failures");

    performance.remove(performance.size() - 1);
    if (performance.isEmpty()) {
        JOptionPane.showMessageDialog(null, "test did not run long enough");
        return null;
    }/*www  .ja v a  2 s . c om*/

    JFreeChart chart;

    int totalCount = 0;
    int totalRevoked = 0;
    int totalFailures = 0;

    for (PerformanceData performanceEntry : performance) {
        series.add(new Second(performanceEntry.getDate()), performanceEntry.getCount());
        totalCount += performanceEntry.getCount();

        revokedSeries.add(new Second(performanceEntry.getDate()), performanceEntry.getRevoked());
        totalRevoked += performanceEntry.getRevoked();

        failureSeries.add(new Second(performanceEntry.getDate()), performanceEntry.getFailures());
        totalFailures += performanceEntry.getFailures();
    }

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    dataset.addSeries(revokedSeries);
    dataset.addSeries(failureSeries);
    chart = ChartFactory.createTimeSeriesChart("eID Trust Service Performance History",
            "Time (interval size " + intervalSize + " msec)", "Number of XKMS requests", dataset, true, false,
            false);

    chart.addSubtitle(new TextTitle(performance.get(0).getDate().toString() + " - "
            + performance.get(performance.size() - 1).getDate().toString()));

    TextTitle info = new TextTitle("Total number of successful requests: " + totalCount);
    info.setTextAlignment(HorizontalAlignment.LEFT);
    info.setPosition(RectangleEdge.BOTTOM);
    chart.addSubtitle(info);

    TextTitle info2 = new TextTitle(
            "Total number of revoked: " + totalRevoked + " expected=" + expectedRevoked);
    info2.setPosition(RectangleEdge.BOTTOM);
    info2.setTextAlignment(HorizontalAlignment.LEFT);
    chart.addSubtitle(info2);

    TextTitle info3 = new TextTitle("Total number of failures: " + totalFailures);
    info3.setPosition(RectangleEdge.BOTTOM);
    info3.setTextAlignment(HorizontalAlignment.LEFT);
    chart.addSubtitle(info3);

    chart.setBackgroundPaint(Color.WHITE);
    XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.WHITE);
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss"));
    ValueAxis valueAxis = plot.getRangeAxis();
    valueAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    plot.setRangeGridlinePaint(Color.black);
    plot.setDomainGridlinePaint(Color.black);
    plot.setRenderer(renderer);

    return chart;
}

From source file:org.zaproxy.zap.extension.customFire.ScanProgressDialog.java

/**
 * //  ww  w . ja va 2  s.c o  m
 * @param dataset
 * @return JFreeChart `
 */
private JFreeChart createChart(final XYDataset dataset) {

    JFreeChart result = ChartFactory.createTimeSeriesChart(null, "Time", "Response/seconds", dataset, true,
            false, false);
    XYPlot plot = result.getXYPlot();
    ValueAxis daxis = plot.getDomainAxis();
    daxis.setAutoRange(true);
    daxis.setAutoRangeMinimumSize(60000.0);

    plot.getRangeAxis().setAutoRangeMinimumSize(20);

    return result;
}

From source file:com.haskins.cloudtrailviewer.feature.MetricsFeature.java

private void showChart(String service) {

    final TimeSeriesCollection chartData = generateTimeSeriesData(service);

    JFreeChart chart = ChartFactory.createTimeSeriesChart(service, "Time", "Calls", chartData, false, true,
            false);/*from ww w .  j av a  2  s.c  o  m*/

    // draw outter line
    XYLineAndShapeRenderer lineAndShapeRenderer = new XYLineAndShapeRenderer();
    lineAndShapeRenderer.setPaint(new Color(64, 168, 228, 75));
    lineAndShapeRenderer.setSeriesShape(0, new Ellipse2D.Double(-3, -3, 6, 6));
    lineAndShapeRenderer.setSeriesShapesFilled(0, true);
    lineAndShapeRenderer.setSeriesShapesVisible(0, true);
    lineAndShapeRenderer.setUseOutlinePaint(true);
    lineAndShapeRenderer.setUseFillPaint(true);

    // draw filled area
    XYAreaRenderer renderer = new XYAreaRenderer();
    renderer.setPaint(new Color(64, 168, 228, 50));

    // configure Plot
    final XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setOutlineVisible(false);

    plot.setDataset(0, chartData);
    plot.setDataset(1, chartData);

    plot.setRenderer(0, lineAndShapeRenderer);
    plot.setRenderer(1, renderer);

    plot.getDomainAxis().setLowerMargin(0);
    plot.getDomainAxis().setUpperMargin(0);

    // format chart title
    TextTitle t = chart.getTitle();
    t.setFont(new Font("Arial", Font.BOLD, 14));

    // Cross Hairs
    xCrosshair = new Crosshair(Double.NaN, Color.GRAY, new BasicStroke(0f));
    xCrosshair.setLabelVisible(true);
    xCrosshair.setLabelGenerator(new DateTimeCrosshairLabelGenerator());

    CrosshairOverlay crosshairOverlay = new CrosshairOverlay();
    crosshairOverlay.addDomainCrosshair(xCrosshair);

    // Create the panel
    chartPanel = new ChartPanel(chart);
    chartPanel.setMinimumDrawWidth(0);
    chartPanel.setMaximumDrawWidth(Integer.MAX_VALUE);
    chartPanel.setMinimumDrawHeight(0);
    chartPanel.setMaximumDrawHeight(Integer.MAX_VALUE);
    chartPanel.setMouseZoomable(true, false);
    chartPanel.setDomainZoomable(true);
    chartPanel.setRangeZoomable(false);
    chartPanel.addChartMouseListener(this);
    chartPanel.addOverlay(crosshairOverlay);

    // update the display
    chartCards.removeAll();
    chartCards.add(chartPanel, "");
    chartCards.revalidate();
}

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getDailyIntegratedStats(Session s) throws CloneNotSupportedException {
    JFreeChart chart;/*  w w  w. j a  v  a  2s  . com*/
    List<DailyStatsModel> stats = (new SafeHibList<DailyStatsModel>(
            s.createQuery("select ds from DailyStatsModel as ds where day<? and day>=? order by day desc")
                    .setDate(0, new Date()).setDate(1, GraphServlet.getStartDate()))).list();
    TimeSeriesCollection theData = new TimeSeriesCollection();
    TimeSeriesCollection theData2 = new TimeSeriesCollection();

    TimeSeries users = new TimeSeries("Total Users", Day.class);
    theData.addSeries(users);

    TimeSeries regulars = new TimeSeries("Regular Members", Day.class);
    theData2.addSeries(regulars);

    int numUsers = Helpers.getGroup("Org").getNumMembers();
    int numReg = Helpers.getGroup("Regular").getNumMembers();

    for (DailyStatsModel ds : stats) {
        Day theDay = new Day(ds.getDay());
        users.add(theDay, numUsers);
        regulars.add(theDay, numReg);
        numUsers -= (ds.getMailinglistsignups() + ds.getSignups() - ds.getDeletions());
        numReg -= (ds.getRegupgrades() - ds.getRegdowngrades());
    }

    chart = ChartFactory.createTimeSeriesChart("Membership", "Day", "Users", theData, true, true, true);

    XYPlot plot = (XYPlot) chart.getPlot();

    NumberAxis axis2 = new NumberAxis("Regular Members");
    plot.setRangeAxis(1, axis2);
    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
    plot.setDataset(1, MovingAverage.createMovingAverage(theData2, "", 14, 0));
    plot.mapDatasetToRangeAxis(1, 1);

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(0);
    renderer.setSeriesStroke(0, new BasicStroke(2.0f));
    renderer = (XYLineAndShapeRenderer) renderer.clone();
    renderer.setSeriesStroke(0, new BasicStroke(2.0f));
    plot.setRenderer(1, renderer);
    return chart;
}

From source file:be.vds.jtbdive.client.view.core.stats.StatChartGenerator.java

private static JFreeChart createLineChart(TimeSeriesCollection collection, String xLabel, String yLabel) {
    JFreeChart chart = ChartFactory.createTimeSeriesChart("", // chart title
            xLabel, // domain axis label
            yLabel, // range axis label
            collection, // data
            true, // include legend
            true, // tooltips
            false // urls
    );/*from w w  w  . j av  a2 s .  c o m*/
    return chart;
}

From source file:net.bioclipse.chart.ChartUtils.java

/**
 * Plot time series//  w  w w .j a  v  a  2  s. co m
 * 
 * @param dataValues
 * @param timeValues
 * @param xLabel X axis label
 * @param yLabel Y axis label
 * @param title Chart title
 * @param dataSource 
 * @param indices 
 */
public static void timeSeries(double[] dataValues, double[] timeValues, String xLabel, String yLabel,
        String title, int[] indices, IEditorPart dataSource) {
    setupData(dataValues, timeValues, xLabel, yLabel, title);
    DefaultXYDataset dataset = new DefaultXYDataset();
    dataset.addSeries(1, values);
    chart = ChartFactory.createTimeSeriesChart(title, xLabel, yLabel, (XYDataset) dataset, false, false, false);

    ChartDescriptor descriptor = new ChartDescriptor(dataSource, indices, ChartConstants.TIME_SERIES, xLabel,
            yLabel);
    chartManager.put(chart, descriptor);

    view.display(chart);
    ChartUtils.currentPlotType = ChartConstants.TIME_SERIES;
}

From source file:org.yccheok.jstock.gui.SellPortfolioTimeChartJDialog.java

private JFreeChart createChart(String name) {
    final JStockOptions jStockOptions = MainFrame.getInstance().getJStockOptions();
    final boolean isFeeCalculationEnabled = jStockOptions.isFeeCalculationEnabled();
    final boolean isPenceToPoundConversionEnabled = jStockOptions.isPenceToPoundConversionEnabled();

    final Portfolio portfolio = (Portfolio) portfolioTreeTableModel.getRoot();
    final int count = portfolio.getChildCount();

    final List<DataEx> dataExs = new ArrayList<DataEx>();

    for (int i = 0; i < count; i++) {
        TransactionSummary transactionSummary = (TransactionSummary) portfolio.getChildAt(i);

        if (transactionSummary.getChildCount() <= 0) {
            continue;
        }//from w w  w.  j a va  2s .  c o m

        Transaction transaction = (Transaction) transactionSummary.getChildAt(0);
        final Date date = transaction.getDate().getTime();

        if (name.equals(cNames[2]) || name.equals(cNames[3])) {
            this.isCumulativeChart = true;
        } else {
            this.isCumulativeChart = false;
        }

        /* Should use reflection technology. */
        if (name.equals(cNames[0]) || name.equals(cNames[2])) {
            if (isPenceToPoundConversionEnabled == false) {
                if (isFeeCalculationEnabled) {
                    dataExs.add(DataEx.newInstance(date,
                            portfolioTreeTableModel.getNetGainLossValue(transactionSummary)));
                } else {
                    dataExs.add(DataEx.newInstance(date,
                            portfolioTreeTableModel.getGainLossValue(transactionSummary)));
                }
            } else {
                if (isFeeCalculationEnabled) {
                    dataExs.add(DataEx.newInstance(date,
                            portfolioTreeTableModel.getNetGainLossValue(transactionSummary) / 100.0));
                } else {
                    dataExs.add(DataEx.newInstance(date,
                            portfolioTreeTableModel.getGainLossValue(transactionSummary) / 100.0));
                }
            }
        } else if (name.equals(cNames[1]) || name.equals(cNames[3])) {
            if (isPenceToPoundConversionEnabled == false) {
                if (isFeeCalculationEnabled) {
                    dataExs.add(DataEx.newInstance(date,
                            -portfolioTreeTableModel.getNetGainLossValue(transactionSummary)));
                } else {
                    dataExs.add(DataEx.newInstance(date,
                            -portfolioTreeTableModel.getGainLossValue(transactionSummary)));
                }
            } else {
                if (isFeeCalculationEnabled) {
                    dataExs.add(DataEx.newInstance(date,
                            -portfolioTreeTableModel.getNetGainLossValue(transactionSummary) / 100.0));
                } else {
                    dataExs.add(DataEx.newInstance(date,
                            -portfolioTreeTableModel.getGainLossValue(transactionSummary) / 100.0));
                }
            }
        }
    }

    Collections.sort(dataExs);
    TimeSeries series = new TimeSeries(name);
    double totalValue = 0;
    for (DataEx dataEx : dataExs) {
        double value = dataEx.value;
        if (!this.isCumulativeChart && series.getValue(new Day(dataEx.date)) != null) {
            value += series.getValue(new Day(dataEx.date)).doubleValue();
        }

        if (this.isCumulativeChart) {
            totalValue += value;
            series.addOrUpdate(new Day(dataEx.date), totalValue);
        } else {
            series.addOrUpdate(new Day(dataEx.date), value);
        }

    }

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);

    JFreeChart chart = ChartFactory.createTimeSeriesChart(name, "date", null, dataset, false, true, false);

    ValueMarker marker = new ValueMarker(0);
    marker.setPaint(Color.black);

    XYPlot plot = (XYPlot) chart.getXYPlot();
    plot.addRangeMarker(marker);

    return chart;

}