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:oscar.oscarEncounter.oscarMeasurements.pageUtil.MeasurementGraphAction2.java

JFreeChart defaultChart(String demographicNo, String typeIdName, String typeIdName2, String patientName,
        String chartTitle) {//from ww  w . j a v  a 2  s  .  c om
    org.jfree.data.time.TimeSeriesCollection dataset = new org.jfree.data.time.TimeSeriesCollection();

    ArrayList<EctMeasurementsDataBean> list = getList(demographicNo, typeIdName);
    String typeYAxisName = "";

    if (typeIdName.equals("BP")) {
        log.debug("Using BP LOGIC FOR type 1 ");
        EctMeasurementsDataBean sampleLine = list.get(0);
        typeYAxisName = sampleLine.getTypeDescription();
        TimeSeries systolic = new TimeSeries("Systolic", Day.class);
        TimeSeries diastolic = new TimeSeries("Diastolic", Day.class);
        for (EctMeasurementsDataBean mdb : list) { // dataVector) {
            String[] str = mdb.getDataField().split("/");

            systolic.addOrUpdate(new Day(mdb.getDateObservedAsDate()), Double.parseDouble(str[0]));
            diastolic.addOrUpdate(new Day(mdb.getDateObservedAsDate()), Double.parseDouble(str[1]));
        }
        dataset.addSeries(diastolic);
        dataset.addSeries(systolic);

    } else {
        log.debug("Not Using BP LOGIC FOR type 1 ");
        // get the name from the TimeSeries
        EctMeasurementsDataBean sampleLine = list.get(0);
        String typeLegendName = sampleLine.getTypeDisplayName();
        typeYAxisName = sampleLine.getTypeDescription(); // this should be the type of measurement

        TimeSeries newSeries = new TimeSeries(typeLegendName, Day.class);
        for (EctMeasurementsDataBean mdb : list) { //dataVector) {
            newSeries.addOrUpdate(new Day(mdb.getDateObservedAsDate()), Double.parseDouble(mdb.getDataField()));
        }
        dataset.addSeries(newSeries);
    }

    JFreeChart chart = ChartFactory.createTimeSeriesChart(chartTitle, "Days", typeYAxisName, dataset, true,
            true, true);

    if (typeIdName2 != null) {
        log.debug("type id name 2" + typeIdName2);

        ArrayList<EctMeasurementsDataBean> list2 = getList(demographicNo, typeIdName2);
        org.jfree.data.time.TimeSeriesCollection dataset2 = new org.jfree.data.time.TimeSeriesCollection();

        log.debug("list2 " + list2);

        EctMeasurementsDataBean sampleLine2 = list2.get(0);
        String typeLegendName = sampleLine2.getTypeDisplayName();
        String typeYAxisName2 = sampleLine2.getTypeDescription(); // this should be the type of measurement

        TimeSeries newSeries = new TimeSeries(typeLegendName, Day.class);
        for (EctMeasurementsDataBean mdb : list2) { //dataVector) {
            newSeries.addOrUpdate(new Day(mdb.getDateObservedAsDate()), Double.parseDouble(mdb.getDataField()));
        }
        dataset2.addSeries(newSeries);

        ////
        final XYPlot plot = chart.getXYPlot();
        final NumberAxis axis2 = new NumberAxis(typeYAxisName2);
        axis2.setAutoRangeIncludesZero(false);
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset2);
        plot.mapDatasetToRangeAxis(1, 1);
        final XYItemRenderer renderer = plot.getRenderer();
        renderer.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
        if (renderer instanceof StandardXYItemRenderer) {
            final StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer;

            rr.setBaseShapesFilled(true);
        }

        final StandardXYItemRenderer renderer2 = new StandardXYItemRenderer();
        renderer2.setSeriesPaint(0, Color.black);
        renderer.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
        plot.setRenderer(1, renderer2);

    }
    return chart;
}

From source file:oscar.oscarEncounter.oscarMeasurements.pageUtil.MeasurementGraphAction2.java

JFreeChart ChartMeds(String demographicNo, String patientName, String chartTitle, String[] drugs) {
    MiscUtils.getLogger().debug("In ChartMeds");
    org.jfree.data.time.TimeSeriesCollection dataset = new org.jfree.data.time.TimeSeriesCollection();
    JFreeChart chart = ChartFactory.createTimeSeriesChart(chartTitle, "Days", "MEDS", dataset, true, true,
            true);//from  ww  w.  j a  va 2 s.  c o m

    XYPlot plot = chart.getXYPlot();
    //            plot.getDomainAxis().setAutoRange(true);
    //            Range rang = plot.getDataRange(plot.getRangeAxis());
    //
    //            log.debug("LEN " + plot.getDomainAxis().getLowerBound() + " ddd " + plot.getDomainAxis().getUpperMargin() + " eee " + plot.getDomainAxis().getLowerMargin());
    //            plot.getDomainAxis().setUpperMargin(plot.getDomainAxis().getUpperMargin()*6);
    //            plot.getDomainAxis().setLowerMargin(plot.getDomainAxis().getLowerMargin()*6);
    //            plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin()*1.7);
    //
    //            plot.getDomainAxis().setUpperMargin(0.9);
    //            plot.getDomainAxis().setLowerMargin(0.9);
    //            plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin() * 4);

    XYTaskDataset drugDataset = getDrugDataSet(demographicNo, drugs);

    SymbolAxis yAxis = new SymbolAxis("Meds", getDrugSymbol(demographicNo, drugs));

    yAxis.setGridBandsVisible(false);
    XYBarRenderer xyrenderer = new XYBarRenderer();
    xyrenderer.setUseYInterval(true);
    xyrenderer.setBarPainter(new StandardXYBarPainter());

    //XYPlot xyplot = new XYPlot(drugDataset, xAxis, yAxis, xyrenderer);
    XYPlot xyplot = new XYPlot(drugDataset, plot.getDomainAxis(), yAxis, xyrenderer);

    xyplot.getDomainAxis().setUpperMargin(0.9);
    xyplot.getDomainAxis().setLowerMargin(0.9);

    CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(new DateAxis("Date/Time"));
    cplot.add(xyplot);

    chart = new JFreeChart(chartTitle, cplot);
    chart.setBackgroundPaint(Color.white);
    return chart;
}

From source file:org.ramadda.geodata.cdmdata.PointDatabaseTypeHandler.java

/**
 * _more_/*from   w ww.j a  v a 2 s.c o  m*/
 *
 *
 * @param request _more_
 * @param entry _more_
 * @param dataset _more_
 *
 * @return _more_
 */
private static JFreeChart createChart(Request request, Entry entry, XYDataset dataset) {
    JFreeChart chart = ChartFactory.createTimeSeriesChart(
            request.getString(ARG_POINT_TIMESERIES_TITLE, entry.getName()), // title
            "Date", // x-axis label
            "", // y-axis label
            dataset, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );

    chart.setBackgroundPaint(Color.white);
    ValueAxis rangeAxis = new NumberAxis("");
    rangeAxis.setVisible(false);
    XYPlot plot = (XYPlot) chart.getPlot();
    if (request.get("gray", false)) {
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
    } else {
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinePaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.lightGray);
    }
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);
    plot.setRangeAxis(0, rangeAxis, false);

    XYItemRenderer r = plot.getRenderer();
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));

    return chart;

}

From source file:de.fau.amos.ChartRenderer.java

/**
 * Creates Chart (JFreeChart object) using TimeSeriesCollection. Used for forecast only.
 * /*from   w  w w. j a v a2s  .c o m*/
 * @param collection TimeSeriesCollection that provides basis for chart.
 * @param time Time where "real" data ends.
 * @param unit Unit of displayed values (kWh,TNF,kWh/TNF)
 * @return Returns finished JFreeChart.
 */
private JFreeChart createForecastChart(final TimeSeriesCollection collection, String time, String unit) {

    // Modification of X-Axis Label
    int day = Integer.parseInt(time.substring(8, 10));
    int month = Integer.parseInt(time.substring(5, 7));
    int year = Integer.parseInt(time.substring(0, 4));
    //get Weekday
    Calendar c = Calendar.getInstance();
    c.set(year, month - 1, day, 0, 0);
    int weekDay = c.get(Calendar.DAY_OF_WEEK);

    String dayString = new DateFormatSymbols(Locale.US).getWeekdays()[weekDay] + ", " + day + ". ";
    String monthString = new DateFormatSymbols(Locale.US).getMonths()[month - 1];
    String xAxisLabel = "" + dayString + monthString + "  " + time.substring(0, 4);

    //Creation of the lineChart
    JFreeChart lineChart = ChartFactory.createTimeSeriesChart("Forecast", // title
            xAxisLabel, // x-axis label
            //            "Energy Consumption "+("1".equals(unit)?"[kWh]":("2".equals(unit)?"[kWh/TNF]":("3".equals(unit)?"[TNF]":""))),       // y-axis label
            ("1".equals(unit) ? "Energy Consumption [kWh]"
                    : ("2".equals(unit) ? "Energy Consumption [kWh/TNF]"
                            : ("3".equals(unit) ? "Produced Pieces [TNF]" : ""))),
            collection, // data
            true, // create legend?
            false, // generate tooltips?
            false // generate URLs?
    );

    //graphical modifications for LineChart
    lineChart.setBackgroundPaint(Color.white);

    XYPlot plot = lineChart.getXYPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(0, 0, 0, 0));

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer() {
        private static final long serialVersionUID = 1L;
        //         Stroke soild = new BasicStroke(2.0f);
        Stroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f,
                new float[] { 10.0f }, 0.0f);

        @Override
        public Stroke getItemStroke(int row, int column) {
            //third series in collection -> forecast collection
            if (row == 2) {
                return dashed;
                //partial dashed->not needed now, maybe later

                //               double x = collection.getXValue(row, column);
                //               
                //               if ( x > 4){
                //                  return dashed;
                //               } else {
                //                  return soild;
                //               } 
            } else
                return super.getItemStroke(row, column);
        }
    };
    renderer.setBaseShapesVisible(false);
    renderer.setBaseShapesFilled(true);
    renderer.setBaseStroke(new BasicStroke(3));
    plot.setRenderer(renderer);

    return lineChart;
}

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

private JFreeChart getListMemberships(Session s, int groupId, UserModel currentUser) {
    final int NUM_MONTHS = 6;
    Logger log = Logger.getLogger(this.getClass());
    JFreeChart chart;//from ww  w .j  a v  a 2 s.  com
    Date startDate;
    TreeMap<Day, Integer> memberChange = new TreeMap<Day, Integer>();
    GroupModel g = (GroupModel) s.get(GroupModel.class, groupId);

    if (g == null) {
        log.warn("Someone requested chapter stats with a bad group id");
    } else if (!Permissions.canAdministerGroupMembership(currentUser, g)) {
        log.warn(currentUser.getUsername() + "tried to access list memberships graph!");
    }

    Calendar cal = GregorianCalendar.getInstance();
    Date now = cal.getTime();
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 1);
    cal.add(Calendar.MONTH, -NUM_MONTHS);
    startDate = cal.getTime();

    //Set Initial Number of Members      
    int initMembers = g.getNumMembers() + g.getNumRecipients();

    //Pull a list of all of the membership start dates
    List starts = s.createQuery("SELECT rm.start, count(*) " + "FROM RoleModel as rm "
            + "WHERE rm.group = :group " + "AND (rm.level = 'r' OR rm.level = 'm') "
            + "AND rm.start > :startDate " + "GROUP BY rm.start ").setEntity("group", g)
            .setDate("startDate", startDate).list();

    for (Object o : starts) {
        Day date = new Day((Date) (((Object[]) o)[0]));
        int change = ((Long) (((Object[]) o)[1])).intValue();
        memberChange.put(date, change);
        initMembers -= change;
    }

    //Pull a list of all of the membership end dates
    List ends = s.createQuery("SELECT rm.end, count(*) " + "FROM RoleModel as rm " + "WHERE rm.group = :group "
            + "AND (rm.level = 'r' OR rm.level = 'm') " + "AND rm.end > :startDate " + "GROUP BY rm.end ")
            .setEntity("group", g).setDate("startDate", startDate).list();

    for (Object o : ends) {
        Day date = new Day((Date) (((Object[]) o)[0]));
        int change = ((Long) (((Object[]) o)[1])).intValue();
        if (memberChange.containsKey(date)) {
            memberChange.put(date, memberChange.get(date) - change);
        } else {
            memberChange.put(date, -change);
        }
        initMembers += change;
    }

    TimeSeriesCollection theData = new TimeSeriesCollection();

    TimeSeries signups = new TimeSeries("List Membership", Day.class);
    theData.addSeries(signups);
    while (startDate.before(now)) {
        Day d = new Day(startDate);
        if (memberChange.containsKey(d)) {
            initMembers += memberChange.get(d);
        }
        signups.add(d, initMembers);
        cal.add(Calendar.DATE, 1);
        startDate = cal.getTime();
    }

    chart = ChartFactory.createTimeSeriesChart("List Members", "Day", "Number of Members", theData, true, true,
            true);

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

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

From source file:org.jfree.chart.demo.DifferenceChartDemo2.java

/**
 * Creates a chart.//from  w  w  w  . java2  s.c  o m
 * 
 * @param dataset  the dataset.
 * 
 * @return The chart.
 */
private JFreeChart createChart(final XYDataset dataset) {
    final JFreeChart chart = ChartFactory.createTimeSeriesChart("Daylight Hours - London, UK", "Date", "Time",
            dataset, true, // legend
            true, // tool tips
            false // URLs
    );
    chart.setBackgroundPaint(Color.white);

    final XYDifferenceRenderer renderer = new XYDifferenceRenderer(Color.blue, Color.blue, false);
    renderer.setStroke(new BasicStroke(2.0f));
    renderer.setSeriesPaint(0, Color.yellow);
    renderer.setSeriesPaint(1, Color.red);
    final XYPlot plot = chart.getXYPlot();
    plot.setRenderer(renderer);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    //        plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));

    final DateAxis domainAxis = new DateAxis("Time");
    domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    plot.setDomainAxis(domainAxis);
    plot.setForegroundAlpha(0.5f);

    final Color c = new Color(255, 60, 24, 63);
    final Marker bst = new IntervalMarker(new Day(28, 3, 2004).getFirstMillisecond(),
            new Day(30, 10, 2004).getFirstMillisecond(), c, new BasicStroke(2.0f), null, null, 1.0f);
    bst.setLabel("British Summer Time");
    bst.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT);
    bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10));
    bst.setLabelTextAnchor(TextAnchor.BASELINE_RIGHT);
    plot.addDomainMarker(bst, Layer.BACKGROUND);

    final DateAxis rangeAxis = new DateAxis("Time");
    rangeAxis.setLowerMargin(0.15);
    rangeAxis.setUpperMargin(0.15);
    plot.setRangeAxis(rangeAxis);
    return chart;
}

From source file:com.zimbra.perf.chart.ChartUtil.java

private List<JFreeChart> createJFReeChart(ChartSettings cs) {

    double minValue = Double.MAX_VALUE;
    double maxValue = Double.MIN_VALUE;
    double d = 0;
    double count = 0;
    double total = 0;
    TimeSeriesCollection data = new TimeSeriesCollection();

    ArrayList<ChartSettings> syntheticSettings = new ArrayList<ChartSettings>();
    for (GroupPlotSettings gps : cs.getGroupPlots()) {
        String groupBy = gps.getGroupBy();
        DataColumn dc = new DataColumn(gps.getInfile(), groupBy);
        StringSeries groupBySeries = mStringSeries.get(dc);
        dc = new DataColumn(gps.getInfile(), gps.getDataColumn());
        DataSeries ds = mDataSeries.get(dc);
        int idx = 0;
        Map<String, List<Integer>> groups = new HashMap<String, List<Integer>>();
        for (StringEntry e : groupBySeries.dataCollection) {
            String g = e.getVal();
            List<Integer> indices = groups.get(g);
            if (indices == null) {
                indices = new ArrayList<Integer>();
                groups.put(g, indices);/*from  w  w w.  java2s  .  c o  m*/
            }
            indices.add(idx);
            idx++;
        }
        for (Map.Entry<String, List<Integer>> g : groups.entrySet()) {
            String groupByValue = g.getKey();
            if (gps.getIgnoreSet().contains(groupByValue))
                continue;
            List<Integer> indices = g.getValue();
            DataSeries syntheticDS = new DataSeries();
            DataColumn c = new DataColumn(gps.getInfile(),
                    GROUP_PLOT_SYNTHETIC + groupByValue + ":" + gps.getDataColumn());
            for (int i : indices) {
                Entry e = ds.get(i);
                syntheticDS.AddEntry(e.getTimestamp(), e.getVal());
            }
            mDataSeries.put(c, syntheticDS);
            PlotSettings syntheticPlot = new PlotSettings(groupByValue, c.getInfile(), c.getColumn(),
                    gps.getShowRaw(), gps.getShowMovingAvg(), gps.getMovingAvgPoints(), gps.getMultiplier(),
                    gps.getDivisor(), gps.getNonNegative(), gps.getPercentTime(), gps.getDataFunction(),
                    gps.getAggregateFunction(), gps.getOptional(), null, null);
            cs.addPlot(syntheticPlot);
            if (cs.getOutDocument() != null) {
                ChartSettings s = new ChartSettings(String.format(cs.getTitle(), groupByValue),
                        cs.getCategory(), String.format(cs.getOutfile(), groupByValue), cs.getXAxis(),
                        cs.getYAxis(), cs.getAllowLogScale(), cs.getPlotZero(), cs.getWidth(), cs.getHeight(),
                        null, cs.getTopPlots(), cs.getTopPlotsType());
                s.addPlot(syntheticPlot);
                syntheticSettings.add(s);
            }
        }
    }
    if (cs.getOutDocument() != null && cs.getGroupPlots().size() != 0) {
        ArrayList<JFreeChart> charts = new ArrayList<JFreeChart>();
        for (ChartSettings c : syntheticSettings) {
            charts.addAll(createJFReeChart(c));
            c.setOutDocument(cs.getOutDocument());
        }
        mSyntheticChartSettings.addAll(syntheticSettings);
        return charts;
    }

    List<PlotSettings> plots = cs.getPlots();
    if (cs.getTopPlots() > 0 && plots.size() > cs.getTopPlots()) {
        String aggregateFunction = cs.getTopPlotsType().name().toLowerCase();
        System.out.println(String.format("Reducing %d to %d plots for chart '%s'", plots.size(),
                cs.getTopPlots(), cs.getTitle()));
        ArrayList<PlotAggregatePair> aggregates = new ArrayList<PlotAggregatePair>();
        for (PlotSettings ps : plots) {
            DataColumn dc = new DataColumn(ps.getInfile(), ps.getDataColumn());
            String key = ps.getInfile() + ":" + ps.getDataColumn() + ":" + ps.getAggregateFunction();
            PlotDataIterator pdIter = new PlotDataIterator(ps, mDataSeries.get(dc));
            double aggregate = mAggregator.compute(pdIter, aggregateFunction, mAggregateStartAt,
                    mAggregateEndAt, key);
            aggregates.add(new PlotAggregatePair(ps, aggregate));
        }
        Collections.sort(aggregates);
        while (aggregates.size() > cs.getTopPlots()) {
            PlotAggregatePair pair = aggregates.remove(0);
            plots.remove(pair.ps);
        }
    }
    for (PlotSettings ps : plots) {
        String columnName = ps.getDataColumn();
        if (columnName == null) {
            columnName = RATIO_PLOT_SYNTHETIC + ps.getRatioTop() + "/" + ps.getRatioBottom();
            String infile = ps.getInfile();

            String[] top = ps.getRatioTop().split("\\+");
            String[] bottom = ps.getRatioBottom().split("\\+");

            DataColumn[] ratioTop = new DataColumn[top.length];
            DataColumn[] ratioBottom = new DataColumn[bottom.length];

            for (int i = 0, j = top.length; i < j; i++)
                ratioTop[i] = new DataColumn(infile, top[i]);
            for (int i = 0, j = bottom.length; i < j; i++)
                ratioBottom[i] = new DataColumn(infile, bottom[i]);

            DataSeries[] topData = new DataSeries[ratioTop.length];
            DataSeries[] bottomData = new DataSeries[ratioBottom.length];

            for (int i = 0, j = ratioTop.length; i < j; i++)
                topData[i] = mDataSeries.get(ratioTop[i]);
            for (int i = 0, j = ratioBottom.length; i < j; i++)
                bottomData[i] = mDataSeries.get(ratioBottom[i]);

            DataSeries ds = new DataSeries();
            for (int i = 0, j = topData[0].size(); i < j; i++) {
                double topValue = 0.0;
                double bottomValue = 0.0;
                double ratio = 0.0;
                Entry lastEntry = null;
                for (int m = 0, n = topData.length; m < n; m++) {
                    Entry e = topData[m].get(i);
                    topValue += e.getVal();
                }
                for (int m = 0, n = bottomData.length; m < n; m++) {
                    Entry e = bottomData[m].get(i);
                    bottomValue += e.getVal();
                    lastEntry = e;
                }
                if (bottomValue != 0.0) {
                    ratio = topValue / bottomValue;
                }
                // should never be null
                assert lastEntry != null;
                ds.AddEntry(lastEntry.getTimestamp(), ratio);
            }
            mDataSeries.put(new DataColumn(infile, columnName), ds);
            ps.setDataColumn(columnName);
        }
        DataColumn dc = new DataColumn(ps.getInfile(), ps.getDataColumn());
        DataSeries ds = mDataSeries.get(dc);
        TimeSeries ts = new TimeSeries(ps.getLegend(), FixedMillisecond.class);
        int numSamples = 0;
        for (PlotDataIterator pdIter = new PlotDataIterator(ps, ds); pdIter.hasNext(); numSamples++) {
            Pair<Date, Double> entry = pdIter.next();
            Date tstamp = entry.getFirst();
            double val = entry.getSecond().doubleValue();
            if (val != 0 || cs.getPlotZero()) {
                if (d < minValue)
                    minValue = val;
                if (d > maxValue)
                    maxValue = val;
                count++;
                total += val;
                try {
                    ts.addOrUpdate(new FixedMillisecond(tstamp), val);
                } catch (SeriesException e) {
                    e.printStackTrace(System.out);
                }
            }
        }
        if (numSamples == 0 && ps.getOptional()) {
            System.out.format("Skipping optional plot %s (no data sample found)\n\n", ps.getLegend());
            continue;
        }
        System.out.format("Adding %d %s points to %s.\n\n", ds.size(), ps.getLegend(), cs.getOutfile());
        if (ps.getShowRaw()) {
            data.addSeries(ts);
        }
        if (ps.getShowMovingAvg()) {
            int numPoints = ps.getMovingAvgPoints();
            if (numPoints == PlotSettings.DEFAULT_PLOT_MOVING_AVG_POINTS) {
                // Display 200 points for moving average.
                // Divide the total number of points by 200 to
                // determine the number of samples to average
                // for each point.
                numPoints = ts.getItemCount() / 200;
            }
            if (numPoints >= 2) {
                TimeSeries ma = MovingAverage.createPointMovingAverage(ts, ps.getLegend() + " (moving avg)",
                        numPoints);
                data.addSeries(ma);
            } else {
                System.out.println("Not enough data to display moving average for " + ps.getLegend());
                data.addSeries(ts);

            }
        }

    }
    // Create chart
    boolean legend = (data.getSeriesCount() > 1);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, cs.getXAxis(), cs.getYAxis(), data, legend,
            false, false);

    // Make Y-axis logarithmic if a spike was detected
    if (cs.getAllowLogScale() && (minValue > 0) && (maxValue > 0) && (maxValue > 20 * (total / count))) {
        if (maxValue / minValue > 100) {
            XYPlot plot = (XYPlot) chart.getPlot();
            ValueAxis oldAxis = plot.getRangeAxis();
            LogarithmicAxis newAxis = new LogarithmicAxis(oldAxis.getLabel());
            plot.setRangeAxis(newAxis);
        }
    }

    mChartMap.put(cs, chart);
    return Arrays.asList(chart);

}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartHelper.java

/***********************************************************************************************
 * Create a simple Chart from the specified XYDataset.
 * Choose a TimeSeriesChart or a XYLineChart appropriately.
 * Called from createCustomisedChart() in each ChartUIComponent subclass.
 *
 *
 * @param dataset/*from w  w w.  j  av  a  2  s  .  c  o m*/
 * @param timezone
 * @param metadatalist
 * @param channelcount
 * @param temperaturechannel
 * @param updatetype
 * @param displaylimit
 * @param channelselector
 * @param debug
 *
 * @return JFreeChart
 */

public static JFreeChart createChart(final XYDataset dataset, final TimeZone timezone,
        final List<Metadata> metadatalist, final int channelcount, final boolean temperaturechannel,
        final DataUpdateType updatetype, final int displaylimit,
        final ChannelSelectorUIComponentInterface channelselector, final boolean debug) {
    final String SOURCE = "ChartHelper.createChart() ";
    final JFreeChart chart;
    final String strTitle;
    final String strLabelX;
    final String strLabelY;
    final XYDataset xyDatasetToDisplay;

    // The set of Metadata available should include the Instrument
    // and any items from the current observation
    strTitle = MetadataHelper.getMetadataValueByKey(metadatalist,
            MetadataDictionary.KEY_OBSERVATION_TITLE.getKey());
    strLabelX = MetadataHelper.getMetadataValueByKey(metadatalist,
            MetadataDictionary.KEY_OBSERVATION_AXIS_LABEL_X.getKey());
    // Axis.Y.0 only in this version
    strLabelY = MetadataHelper.getMetadataValueByKey(metadatalist,
            MetadataDictionary.KEY_OBSERVATION_AXIS_LABEL_Y.getKey() + MetadataDictionary.SUFFIX_SERIES_ZERO);

    // Transform the XYdataset in accordance with the current ChannelSelection Mode before displaying

    channelselector.debugSelector(debug, SOURCE);

    xyDatasetToDisplay = copyTransformedXYDataset(dataset, timezone, updatetype, displaylimit,
            channelselector.isDecimating(), channelselector.getChannelSelectionModes());
    if (dataset instanceof TimeSeriesCollection) {
        chart = ChartFactory.createTimeSeriesChart(strTitle, strLabelX, strLabelY, xyDatasetToDisplay,
                channelselector.hasLegend(), true, false);
    } else {
        chart = ChartFactory.createXYLineChart(strTitle, strLabelX, strLabelY, xyDatasetToDisplay,
                PlotOrientation.VERTICAL, channelselector.hasLegend(), true, false);
    }

    if ((chart != null) && (chart.getXYPlot() != null) && (chart.getXYPlot().getRangeAxis() != null)) {
        final Stroke strokeCrosshair;
        final XYPlot plot;
        final XYItemRenderer renderer;

        chart.setBackgroundPaint(UIComponentPlugin.DEFAULT_COLOUR_CANVAS.getColor());

        // Experimental chart configuration
        chart.getTitle().setFont(UIComponentPlugin.DEFAULT_FONT.getFont().deriveFont(20.0f));

        plot = chart.getXYPlot();
        plot.setBackgroundPaint(COLOR_PLOT);
        plot.setDomainGridlinePaint(COLOR_GRIDLINES);
        plot.setRangeGridlinePaint(COLOR_GRIDLINES);
        plot.setAxisOffset(PLOT_RECTANGLE_INSETS);

        plot.setDomainCrosshairVisible(true);
        plot.setDomainCrosshairLockedOnData(false);
        plot.setRangeCrosshairVisible(false);

        // Make the Crosshair more visible by changing the width from the default
        strokeCrosshair = new BasicStroke(2.0f, // The width of this BasicStroke
                BasicStroke.CAP_BUTT, // The decoration of the ends of a BasicStroke
                BasicStroke.JOIN_BEVEL, // The decoration applied where path segments meet
                0.0f, // The limit to trim the miter join
                new float[] { 2.0f, 2.0f }, // The array representing the dashing pattern
                0.0f); // The offset to start the dashing pattern
        plot.setDomainCrosshairStroke(strokeCrosshair);

        renderer = plot.getRenderer();

        if ((renderer != null) && (renderer instanceof XYLineAndShapeRenderer)) {
            final XYLineAndShapeRenderer xyItemRenderer;
            int intSeriesCount;

            xyItemRenderer = (XYLineAndShapeRenderer) renderer;

            xyItemRenderer.setBaseLinesVisible(true);
            xyItemRenderer.setBaseShapesVisible(false);
            xyItemRenderer.setBaseShapesFilled(true);
            xyItemRenderer.setItemLabelsVisible(true);

            // Set the shape for the Chart legend items
            ChartUIHelper.setLegendShape(xyItemRenderer);

            // Colour only as many Series as we know about
            intSeriesCount = 0;

            // Examine the state of each channel's selection
            for (int channel = 0; channel < channelcount; channel++) {
                final ChannelSelectionMode selectionMode;

                if ((channelselector.getChannelSelectionModes() != null)
                        && (channelselector.getChannelSelectionModes().size() == channelcount)) {
                    // If there is a ChannelSelector, get the gain setting, or OFF
                    selectionMode = channelselector.getChannelSelectionModes().get(channel);
                } else if (!channelselector.showChannels()) {
                    // If there is no ChannelSelector, we assume that all Channels are ON, at X1
                    selectionMode = ChannelSelectionMode.X1;
                } else {
                    // Not sure what to do, so just show all
                    selectionMode = ChannelSelectionMode.X1;
                }

                if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                    final ColourInterface colour;

                    colour = MetadataHelper.getChannelColour(metadatalist, channel, temperaturechannel);

                    MetadataHelper.showMetadataList(metadatalist, SOURCE + " COLOURS FOR CHART",
                            LOADER_PROPERTIES.isMetadataDebug());

                    if (colour != null) {
                        // Map the Colour to the Series
                        xyItemRenderer.setSeriesPaint(intSeriesCount, colour.getColor());
                    } else {
                        // Use the default colour if the metadata doesn't have it
                        LOGGER.error(SOURCE
                                + "The channel colour was missing or incorrectly specified in the Metadata, using default colour"
                                + " [channel=" + channel + "]");
                        xyItemRenderer.setSeriesPaint(intSeriesCount,
                                ChartUIHelper.getStandardColour(channel).getColor());
                    }

                    // Prepare for the next Series
                    intSeriesCount++;
                }
            }
        }
    }

    return (chart);
}

From source file:net.sf.fspdfs.chartthemes.spring.GenericChartTheme.java

protected JFreeChart createTimeSeriesChart() throws JRException {
    String timeAxisLabel = (String) evaluateExpression(
            ((JRTimeSeriesPlot) getPlot()).getTimeAxisLabelExpression());
    String valueAxisLabel = (String) evaluateExpression(
            ((JRTimeSeriesPlot) getPlot()).getValueAxisLabelExpression());

    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    JFreeChart jfreeChart = ChartFactory.createTimeSeriesChart(
            (String) evaluateExpression(getChart().getTitleExpression()), timeAxisLabel, valueAxisLabel,
            (TimeSeriesCollection) getDataset(), isShowLegend(), true, false);

    configureChart(jfreeChart, getPlot());

    XYPlot xyPlot = (XYPlot) jfreeChart.getPlot();
    JRTimeSeriesPlot timeSeriesPlot = (JRTimeSeriesPlot) getPlot();

    XYLineAndShapeRenderer lineRenderer = (XYLineAndShapeRenderer) xyPlot.getRenderer();

    boolean isShowShapes = timeSeriesPlot.getShowShapes() == null ? true
            : timeSeriesPlot.getShowShapes().booleanValue();
    boolean isShowLines = timeSeriesPlot.getShowLines() == null ? true
            : timeSeriesPlot.getShowLines().booleanValue();
    lineRenderer.setBaseLinesVisible(isShowLines);
    lineRenderer.setBaseShapesVisible(isShowShapes);

    // Handle the axis formating for the category axis
    configureAxis(xyPlot.getDomainAxis(), timeSeriesPlot.getTimeAxisLabelFont(),
            timeSeriesPlot.getTimeAxisLabelColor(), timeSeriesPlot.getTimeAxisTickLabelFont(),
            timeSeriesPlot.getTimeAxisTickLabelColor(), timeSeriesPlot.getTimeAxisTickLabelMask(),
            timeSeriesPlot.getTimeAxisVerticalTickLabels(), timeSeriesPlot.getOwnTimeAxisLineColor(), false,
            (Comparable) evaluateExpression(timeSeriesPlot.getDomainAxisMinValueExpression()),
            (Comparable) evaluateExpression(timeSeriesPlot.getDomainAxisMaxValueExpression()));

    // Handle the axis formating for the value axis
    configureAxis(xyPlot.getRangeAxis(), timeSeriesPlot.getValueAxisLabelFont(),
            timeSeriesPlot.getValueAxisLabelColor(), timeSeriesPlot.getValueAxisTickLabelFont(),
            timeSeriesPlot.getValueAxisTickLabelColor(), timeSeriesPlot.getValueAxisTickLabelMask(),
            timeSeriesPlot.getValueAxisVerticalTickLabels(), timeSeriesPlot.getOwnValueAxisLineColor(), true,
            (Comparable) evaluateExpression(timeSeriesPlot.getRangeAxisMinValueExpression()),
            (Comparable) evaluateExpression(timeSeriesPlot.getRangeAxisMaxValueExpression()));

    return jfreeChart;
}

From source file:skoa.helpers.Graficos.java

/*********************************************************************************************************
 * FUNCIONES PARA CREAR LOS GRFICOS DE LA CONSULTA D! MANIPULANDO LOS DATOS OBTENIDOS DE LAS CONSULTAS.*
 *********************************************************************************************************/
private void difPorc() {
    //Aplicarle la frmula a los valores de las dos direcciones, obteniendo un slo fichero.
    aplicarFormula(1); //Se le aplica con porcentajes.
    //En este tipo de consultas, buscamos el tipo que es y la unidad, para que se vean.
    String tipo = unidad.substring(0, unidad.indexOf("\t"));
    unidad = unidad.substring(unidad.indexOf("\t") + 1);
    if (unidad.indexOf("C") >= 0)
        unidad = "C";
    TimeSeries serie = obtenerSerieEvolucion2(); //Reutilizamos este cdigo.
    TimeSeriesCollection dataset = new TimeSeriesCollection(serie); //Slo se obtiene una curva.
    JFreeChart grafica = ChartFactory.createTimeSeriesChart("Valores medidos de las direcciones de grupo", //titulo
            "Fechas", //titulo eje x
            "Mediciones en " + tipo + " " + "(" + unidad + ")", //titulo eje y
            dataset, //dataset
            true, //leyenda
            true, //tooltips
            false); //configure chart to generate URLs?

    //Dar color a cada categoria
    grafica.setBackgroundPaint(Color.WHITE); //Color del fondo del grfico
    if (fechaInicial.equals("") & fechaFinal.equals("")) { //Si estn vacas es porque no hay resultados para ese intervalo.
        fechaInicial = " ? ";
        fechaFinal = " ? ";
    }//from  www .ja  v a  2  s  .c o  m
    TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal,
            new Font("SanSerif", Font.ITALIC, 12));
    grafica.addSubtitle(t);
    try {
        ChartUtilities.saveChartAsJPEG(new File(ruta + "DiferenciasSmall.jpg"), grafica, 400, 300);
        ChartUtilities.saveChartAsJPEG(new File(ruta + "DiferenciasBig.jpg"), grafica, 900, 600);
    } catch (IOException e1) {
        System.err.println("Problem occurred creating chart.");
    }
}