private static JFreeChart createChart(TableXYDataset tablexydataset) {
   DateAxis dateaxis = new DateAxis("Date");
   dateaxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
   dateaxis.setLowerMargin(0.01D);
   dateaxis.setUpperMargin(0.01D);
   NumberAxis numberaxis = new NumberAxis("Count");
   numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
   numberaxis.setUpperMargin(0.10000000000000001D);
   StackedXYBarRenderer stackedxybarrenderer = new StackedXYBarRenderer(0.14999999999999999D);
   stackedxybarrenderer.setDrawBarOutline(false);
   stackedxybarrenderer.setBaseItemLabelsVisible(true);
   stackedxybarrenderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
   stackedxybarrenderer.setBasePositiveItemLabelPosition(
       new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER));
   stackedxybarrenderer.setBaseToolTipGenerator(
       new StandardXYToolTipGenerator(
           "{0} : {1} = {2}", new SimpleDateFormat("yyyy"), new DecimalFormat("0")));
   XYPlot xyplot = new XYPlot(tablexydataset, dateaxis, numberaxis, stackedxybarrenderer);
   JFreeChart jfreechart = new JFreeChart("Holes-In-One / Double Eagles", xyplot);
   jfreechart.removeLegend();
   jfreechart.addSubtitle(new TextTitle("PGA Tour, 1983 to 2003"));
   TextTitle texttitle =
       new TextTitle(
           "http://www.golfdigest.com/majors/masters/index.ssf?/majors/masters/gw20040402albatross.html",
           new Font("Dialog", 0, 8));
   jfreechart.addSubtitle(texttitle);
   jfreechart.setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
   LegendTitle legendtitle = new LegendTitle(xyplot);
   legendtitle.setBackgroundPaint(Color.white);
   legendtitle.setFrame(new BlockBorder());
   legendtitle.setPosition(RectangleEdge.BOTTOM);
   jfreechart.addSubtitle(legendtitle);
   return jfreechart;
 }
 /*     */ private static JFreeChart createChart(XYDataset dataset) /*     */ {
   /*  93 */ JFreeChart chart =
       ChartFactory.createTimeSeriesChart(
           "Legal & General Unit Trust Prices",
           "Date",
           "Price Per Unit",
           dataset,
           true,
           true,
           false);
   /*     */
   /* 103 */ chart.setBackgroundPaint(Color.white);
   /*     */
   /* 105 */ XYPlot plot = (XYPlot) chart.getPlot();
   /* 106 */ plot.setBackgroundPaint(Color.lightGray);
   /* 107 */ plot.setDomainGridlinePaint(Color.white);
   /* 108 */ plot.setRangeGridlinePaint(Color.white);
   /* 109 */ plot.setAxisOffset(new RectangleInsets(5.0D, 5.0D, 5.0D, 5.0D));
   /* 110 */ plot.setDomainCrosshairVisible(true);
   /* 111 */ plot.setRangeCrosshairVisible(true);
   /*     */
   /* 113 */ XYItemRenderer r = plot.getRenderer();
   /* 114 */ if ((r instanceof XYLineAndShapeRenderer)) {
     /* 115 */ XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
     /* 116 */ renderer.setBaseShapesVisible(true);
     /* 117 */ renderer.setBaseShapesFilled(true);
     /* 118 */ renderer.setDrawSeriesLineAsPath(true);
     /*     */ }
   /*     */
   /* 121 */ DateAxis axis = (DateAxis) plot.getDomainAxis();
   /* 122 */ axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
   /*     */
   /* 124 */ return chart;
   /*     */ }
  public JFreeChart createJFreeChart(XYDataset dataset) {
    // System.out.println(dataset);
    JFreeChart chart =
        ChartFactory.createTimeSeriesChart(
            "Visualization", // title
            "Date-Time", // x-axis label
            "Readings", // y-axis label
            dataset, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
            );

    chart.setBackgroundPaint(Color.white);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.black);
    plot.setRangeGridlinePaint(Color.black);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
      XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
      // renderer.setSeriesStroke(0, new BasicStroke(1.1f));
      // plot.setRenderer(renderer);
    }

    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("d-M-yy H:m:s"));

    return chart;
  }
示例#4
0
  private JFreeChart buildChart(TimeSeriesCollection dataset, String title, boolean endPoints) {
    // Create the chart
    JFreeChart chart =
        ChartFactory.createTimeSeriesChart(title, "Date", "Price", dataset, true, true, false);

    // Display each series in the chart with its point shape in the legend
    LegendTitle sl = chart.getLegend();
    // sl.setDisplaySeriesShapes(true);

    // Setup the appearance of the chart
    chart.setBackgroundPaint(Color.white);
    XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(UnitType.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    // Display data points or just the lines?
    if (endPoints) {
      XYItemRenderer renderer = plot.getRenderer();
      if (renderer instanceof StandardXYItemRenderer) {
        StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer;
        // rr.setPlotShapes(true);
        rr.setShapesFilled(true);
        rr.setItemLabelsVisible(true);
      }
    }

    // Tell the chart how we would like dates to read
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
    return chart;
  }
  private JFreeChart createChart(XYDataset dataset) {

    JFreeChart chart =
        ChartFactory.createTimeSeriesChart(
            "Updating time series chart", "Date", "Value", dataset, true, true, false);

    chart.setBackgroundPaint(Color.white);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
      XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
      renderer.setBaseShapesVisible(true);
      renderer.setBaseShapesFilled(true);
      renderer.setDrawSeriesLineAsPath(true);
    }

    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy-dd HH:mm:ss"));

    return chart;
  }
 private static JFreeChart createChart(XYDataset xydataset) {
   JFreeChart jfreechart =
       ChartFactory.createTimeSeriesChart(
           "Exercise Chart", "Elapsed Time", "Beats Per Minute", xydataset, true, true, false);
   jfreechart.setBackgroundPaint(Color.white);
   XYPlot xyplot = (XYPlot) jfreechart.getPlot();
   xyplot.setBackgroundPaint(Color.lightGray);
   xyplot.setDomainGridlinePaint(Color.white);
   xyplot.setRangeGridlinePaint(Color.white);
   xyplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
   xyplot.setDomainCrosshairVisible(true);
   xyplot.setRangeCrosshairVisible(true);
   org.jfree.chart.renderer.xy.XYItemRenderer xyitemrenderer = xyplot.getRenderer();
   if (xyitemrenderer instanceof XYLineAndShapeRenderer) {
     XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyitemrenderer;
     xylineandshaperenderer.setBaseShapesVisible(true);
     xylineandshaperenderer.setBaseShapesFilled(true);
   }
   DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
   Minute minute = new Minute(0, 9, 1, 10, 2006);
   RelativeDateFormat relativedateformat = new RelativeDateFormat(minute.getFirstMillisecond());
   relativedateformat.setSecondFormatter(new DecimalFormat("00"));
   dateaxis.setDateFormatOverride(relativedateformat);
   return jfreechart;
 }
 private JFreeChart createChart(IntervalXYDataset intervalxydataset) {
   JFreeChart jfreechart =
       ChartFactory.createXYBarChart(
           frameTitle,
           X_LABEL,
           true,
           Y_LABEL,
           intervalxydataset,
           PlotOrientation.VERTICAL,
           true,
           false,
           false);
   jfreechart.addSubtitle(new TextTitle(SUB_TITLE, new Font("Dialog", 2, 10)));
   jfreechart.setBackgroundPaint(Color.white);
   XYPlot xyplot = (XYPlot) jfreechart.getPlot();
   XYBarRenderer xybarrenderer = (XYBarRenderer) xyplot.getRenderer();
   StandardXYToolTipGenerator standardxytooltipgenerator =
       new StandardXYToolTipGenerator(
           "{1} = {2}", new SimpleDateFormat("yyyy"), new DecimalFormat("0"));
   xybarrenderer.setBaseToolTipGenerator(standardxytooltipgenerator);
   xybarrenderer.setMargin(0.10000000000000001D);
   xyplot.setBackgroundPaint(Color.lightGray);
   xyplot.setRangeGridlinePaint(Color.white);
   DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
   dateaxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
   dateaxis.setLowerMargin(0.01D);
   dateaxis.setUpperMargin(0.01D);
   return jfreechart;
 }
示例#8
0
  public Chart(String title, String timeAxis, String valueAxis, TimeSeries data) {
    try {
      // Build the datasets
      dataset.addSeries(data);

      // Create the chart
      JFreeChart chart =
          ChartFactory.createTimeSeriesChart(
              title, timeAxis, valueAxis, dataset, true, true, false);

      // Setup the appearance of the chart
      chart.setBackgroundPaint(Color.white);
      XYPlot plot = chart.getXYPlot();
      plot.setBackgroundPaint(Color.lightGray);
      plot.setDomainGridlinePaint(Color.white);
      plot.setRangeGridlinePaint(Color.white);
      plot.setAxisOffset(new RectangleInsets(UnitType.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
      plot.setDomainCrosshairVisible(true);
      plot.setRangeCrosshairVisible(true);

      // Tell the chart how we would like dates to read
      DateAxis axis = (DateAxis) plot.getDomainAxis();
      axis.setDateFormatOverride(new SimpleDateFormat("EEE HH"));

      this.add(new ChartPanel(chart));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * This method renders a line chart of income and expense entries over 1-month intervals
   *
   * @param dataset
   * @return financesLineChart_PNL
   */
  private ChartPanel renderLineChart(XYDataset dataset) {

    // Create JFreeChart with dataSet
    JFreeChart lineChart =
        ChartFactory.createTimeSeriesChart("", "", "Amount", dataset, true, true, false);

    // Change the x-axis (time interval) format
    XYPlot plot = (XYPlot) lineChart.getPlot();
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));

    // Change the chart's visual properties
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
      XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
      renderer.setBaseShapesVisible(true);
      renderer.setBaseShapesFilled(true);
      renderer.setDrawSeriesLineAsPath(true);
    }

    // Create and format the chart panel
    ChartPanel financesLineChart_PNL =
        new ChartPanel(lineChart, 600, 250, 200, 100, 800, 300, true, true, true, true, true, true);
    financesLineChart_PNL.setSize(800, 300);

    return financesLineChart_PNL;
  }
示例#10
0
  /**
   * Creates a chart.
   *
   * @param dataset a dataset.
   * @return A chart.
   */
  private static JFreeChart createChart(XYDataset dataset) {
    JFreeChart chart =
        ChartFactory.createTimeSeriesChart(
            "Rapporto Entrata/uscita nel tempo", // title
            "Date", // x-axis label
            "Quantita", // y-axis label
            dataset, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
            );

    chart.setBackgroundPaint(Color.white);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
      XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
      renderer.setBaseShapesVisible(true);
      renderer.setBaseShapesFilled(true);
      renderer.setDrawSeriesLineAsPath(true);
    }

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

    return chart;
  }
示例#11
0
  private JFreeChart makeChart() throws KeyedException {

    if (chartSeries.size() == 0) throw new IllegalStateException("addChartSeries() not called");

    if (range == null) {
      for (ChartSeries s : chartSeries) {
        if (range == null) range = s.getTimeSeries().getRange();
        else range = range.union(s.getTimeSeries().getRange());
      }
    }

    // use number axis for dates, with special formatter
    DateAxis dateAxis = new DateAxis();
    dateAxis.setDateFormatOverride(new CustomDateFormat("M/d/y"));
    if (range.getTimeDomain().getLabel().equals("workweek"))
      dateAxis.setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());

    // combined plot with shared date axis
    CombinedDomainXYPlot plot = new CombinedDomainXYPlot(dateAxis);

    for (ChartSeries s : chartSeries) {
      makeSubPlot(plot, s);
    }

    // make the chart, remove the legend, set the title
    JFreeChart chart = new JFreeChart(plot);
    if (!withLegend) chart.removeLegend();
    chart.setBackgroundPaint(Color.white);
    chart.setTitle(new TextTitle(title));

    return chart;
  }
  private JFreeChart createChart(String chartType) {
    CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis("Date"));
    JFreeChart chart = new JFreeChart(getEditorInput().getName(), plot);
    chart.setBackgroundPaint(Color.white);

    TimeSeriesCollection dataset = createTotalDataset();
    StandardXYItemRenderer standardXYItemRenderer = new StandardXYItemRenderer();
    standardXYItemRenderer.setBaseToolTipGenerator(
        StandardXYToolTipGenerator.getTimeSeriesInstance());
    XYPlot subplot1 = new XYPlot(dataset, null, new NumberAxis("Value"), standardXYItemRenderer);
    plot.add(subplot1, 70);
    subplot1.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    subplot1.setDomainCrosshairVisible(true);
    subplot1.setRangeCrosshairVisible(true);

    XYAreaRenderer xyAreaRenderer = new XYAreaRenderer();
    xyAreaRenderer.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
    XYPlot subplot2 =
        new XYPlot(createGainLossDataset(), null, new NumberAxis("Gain/Loss"), xyAreaRenderer);
    subplot2.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    subplot2.setDomainCrosshairVisible(true);
    subplot2.setRangeCrosshairVisible(true);
    plot.add(subplot2, 30);

    plot.setDrawingSupplier(new PeanutsDrawingSupplier());

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

    timeChart = new TimeChart(chart, dataset);
    timeChart.setChartType(chartType);

    return chart;
  }
 private static JFreeChart createChart() {
   DateAxis dateaxis = new DateAxis("Date");
   dateaxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
   NumberAxis numberaxis = new NumberAxis("Value");
   IntervalXYDataset intervalxydataset = createDataset1();
   XYBarRenderer xybarrenderer = new XYBarRenderer(0.20000000000000001D);
   xybarrenderer.setBaseToolTipGenerator(
       new StandardXYToolTipGenerator(
           "{0}: ({1}, {2})", new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));
   XYPlot xyplot = new XYPlot(intervalxydataset, dateaxis, numberaxis, xybarrenderer);
   NumberAxis numberaxis1 = new NumberAxis("Value 2");
   xyplot.setRangeAxis(1, numberaxis1);
   XYDataset xydataset = createDataset2A();
   StandardXYItemRenderer standardxyitemrenderer = new StandardXYItemRenderer();
   standardxyitemrenderer.setBaseToolTipGenerator(
       new StandardXYToolTipGenerator(
           "{0}: ({1}, {2})", new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));
   xyplot.setDataset(1, xydataset);
   xyplot.setRenderer(1, standardxyitemrenderer);
   XYDataset xydataset1 = createDataset2B();
   xyplot.setDataset(2, xydataset1);
   xyplot.setRenderer(2, new StandardXYItemRenderer());
   xyplot.mapDatasetToRangeAxis(2, 1);
   xyplot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
   xyplot.setOrientation(PlotOrientation.VERTICAL);
   JFreeChart jfreechart =
       new JFreeChart("Overlaid XYPlot Demo 2", JFreeChart.DEFAULT_TITLE_FONT, xyplot, true);
   ChartUtilities.applyCurrentTheme(jfreechart);
   return jfreechart;
 }
示例#14
0
  public JPanel createChart(
      Date from,
      Date to,
      StockInfo stock1,
      StockInfo stock2,
      Color color1,
      Color color2,
      StockPriceType priceType) {

    LOG.info(
        "Generating chart for tickers:"
            + stock1.getTickerSymbol()
            + " & "
            + stock2.getTickerSymbol());

    String chartTitle = df.format(from) + " to " + df.format(to) + " " + priceType;
    XYDataset dataset1 = createDataset(stock1, priceType);
    XYDataset dataset2 = createDataset(stock2, priceType);

    JFreeChart chart =
        ChartFactory.createTimeSeriesChart(
            chartTitle,
            DOMAIN_AXIS_TITLE,
            stock1.getTickerSymbol() + RANGE_AXIS_SUFFIX,
            dataset1,
            true,
            true,
            false);

    XYPlot plot = chart.getXYPlot();
    NumberAxis axis2 = new NumberAxis(stock2.getTickerSymbol() + RANGE_AXIS_SUFFIX);
    Font tickLabelFont = axis2.getTickLabelFont().deriveFont(11.0F);
    Font labelFont = axis2.getLabelFont().deriveFont(15.0F).deriveFont(Font.BOLD);
    axis2.setTickLabelFont(tickLabelFont);
    axis2.setLabelFont(labelFont);
    axis2.setAutoRangeIncludesZero(false);
    plot.setRangeAxis(1, axis2);
    plot.setDataset(1, dataset2);
    plot.mapDatasetToRangeAxis(1, 1);

    StandardXYItemRenderer renderer = new StandardXYItemRenderer();
    renderer.setSeriesPaint(0, color1);
    renderer.setBaseShapesVisible(true);
    renderer.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
    plot.setRenderer(renderer);

    StandardXYItemRenderer renderer2 = new StandardXYItemRenderer();
    renderer2.setSeriesPaint(0, color2);
    renderer2.setBaseShapesVisible(true);
    renderer2.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
    plot.setRenderer(1, renderer2);

    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(df);

    ChartPanel chartPanel = new ChartPanel(chart);

    return chartPanel;
  }
  /** Sets the correct start and end dates and date format. */
  protected void formatChartAxes(JFreeChart chart, DateTime start, DateTime end) {
    XYPlot plot = chart.getXYPlot();
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setMaximumDate(end.plusDays(1).toDateMidnight().toDate());
    axis.setMinimumDate(start.toDateMidnight().toDate());
    axis.setDateFormatOverride(new SimpleDateFormat("EEE d.M."));

    axis.setStandardTickUnits(tickUnits);

    plot.setDomainGridlinePaint(GRIDLINE_COLOR);
    plot.setRangeGridlinePaint(GRIDLINE_COLOR);
  }
  public JFreeChart buildChart(ResultSet rs) throws SQLException {

    List<PlotBuilder> plotBuilders = new ArrayList<PlotBuilder>();

    {
      AmountCurrencyPlotBuilder amtCurrencyBuilder = new AmountCurrencyPlotBuilder();
      amtCurrencyBuilder.setPlotWeight(3);
      plotBuilders.add(amtCurrencyBuilder);

      TxCountPlotBuilder txCountBuilder = new TxCountPlotBuilder();
      txCountBuilder.setPlotWeight(2);
      plotBuilders.add(txCountBuilder);

      PointGivenPlotBuilder ptGivenBuilder = new PointGivenPlotBuilder();
      ptGivenBuilder.setPlotWeight(3);
      plotBuilders.add(ptGivenBuilder);
    }

    // add the records to all builders

    while (rs.next()) {

      for (PlotBuilder plotBuilder : plotBuilders) {

        double value = plotBuilder.getDoubleValue(rs);
        Date date = rs.getTimestamp("transdate_str");

        plotBuilder.addValue(date, value);
      }
    } // has more records

    // create domain axis
    DateAxis domainAxis = new DateAxis("Date");
    domainAxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));

    // create the main plot and add all subplots into it.
    CombinedDomainXYPlot plot = new CombinedDomainXYPlot(domainAxis);
    for (PlotBuilder plotBuilder : plotBuilders) {
      XYPlot subplot = plotBuilder.buildPlot();
      subplot.setNoDataMessage("No Data Available");
      subplot.setNoDataMessagePaint(Color.RED);

      plot.add(subplot, plotBuilder.getPlotWeight());
    }

    // create the chart object.
    JFreeChart chart =
        new JFreeChart("Daily Transaction Report", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    chart.setAntiAlias(true);
    chart.setTextAntiAlias(true);

    return chart;
  }
示例#17
0
  public JFreeChart makegraph(Second g_start, Second g_end) {
    // read
    XYDataset readset = this.createread();
    XYItemRenderer minichart1 = new StandardXYItemRenderer();
    minichart1.setSeriesPaint(0, kSarConfig.color1);
    minichart1.setBaseStroke(kSarConfig.DEFAULT_STROKE);
    XYPlot subplot1 = new XYPlot(readset, null, new NumberAxis("Read"), minichart1);
    // writ
    XYDataset writset = this.createwrit();
    XYItemRenderer minichart2 = new StandardXYItemRenderer();
    minichart2.setSeriesPaint(0, kSarConfig.color2);
    minichart1.setSeriesPaint(1, kSarConfig.color3);
    minichart2.setBaseStroke(kSarConfig.DEFAULT_STROKE);
    XYPlot subplot2 = new XYPlot(writset, null, new NumberAxis("Write"), minichart2);
    // wcache
    XYDataset wcacheset = this.createwcache();
    XYItemRenderer minichart3 = new StandardXYItemRenderer();
    minichart3.setSeriesPaint(0, kSarConfig.color4);
    minichart3.setBaseStroke(kSarConfig.DEFAULT_STROKE);
    XYPlot subplot3 = new XYPlot(wcacheset, null, new NumberAxis("%wcache"), minichart3);
    // rcache
    XYDataset rcacheset = this.creatercache();
    XYItemRenderer minichart4 = new StandardXYItemRenderer();
    minichart4.setSeriesPaint(0, kSarConfig.color5);
    minichart4.setBaseStroke(kSarConfig.DEFAULT_STROKE);
    XYPlot subplot4 = new XYPlot(rcacheset, null, new NumberAxis("%rcache"), minichart4);
    // PANEL
    CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis(""));
    plot.add(subplot1, 1);
    plot.add(subplot2, 1);
    plot.add(subplot3, 1);
    plot.add(subplot4, 1);
    plot.setOrientation(PlotOrientation.VERTICAL);
    JFreeChart mychart = new JFreeChart(this.getGraphTitle(), kSarConfig.DEFAULT_FONT, plot, true);
    if (setbackgroundimage(mychart) == 1) {
      subplot1.setBackgroundPaint(null);
      subplot2.setBackgroundPaint(null);
      subplot3.setBackgroundPaint(null);
      subplot4.setBackgroundPaint(null);
    }
    if (g_start != null) {
      DateAxis dateaxis1 = (DateAxis) mychart.getXYPlot().getDomainAxis();
      dateaxis1.setRange(g_start.getStart(), g_end.getEnd());
    }

    bufferrcachetrigger.setTriggerValue(kSarConfig.hpuxbufferrcachetrigger);
    bufferrcachetrigger.tagMarker(subplot4);

    return mychart;
  }
示例#18
0
  /**
   * Creates a chart.
   *
   * @param dataset a dataset.
   * @return A chart.
   */
  private JFreeChart createChart(Gantt gantt, IntervalCategoryDataset dataset) {

    JFreeChart chart =
        ChartFactory.createGanttChart(
            "Solution Gantt", // title
            "Operators", // x-axis label
            "Time", // y-axis label
            null, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
            );

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

    Paint p = getBackgroundColorGradient();
    chart.setBackgroundPaint(p);

    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.black);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setOrientation(PlotOrientation.HORIZONTAL);

    DateAxis xaxis = (DateAxis) plot.getRangeAxis();
    xaxis.setDateFormatOverride(new VertexDateFormat());
    xaxis.setPositiveArrowVisible(true);

    DefaultDrawingSupplier d = new DefaultDrawingSupplier();

    plot.setDrawingSupplier(d);
    GanttRenderer ren = new MyGanttRenderer();

    for (GanttElement element : gantt.getElementSet()) {
      ((MyGanttRenderer) ren).addColor(element.getTitle(), element.getColor());
    }

    ren.setSeriesItemLabelsVisible(0, false);
    ren.setSeriesVisibleInLegend(0, false);
    ren.setSeriesItemLabelGenerator(0, new IntervalCategoryItemLabelGenerator());
    ren.setSeriesToolTipGenerator(0, new MapperGanttToolTipGenerator());

    ren.setAutoPopulateSeriesShape(false);

    plot.setRenderer(ren);

    plot.setDataset(dataset);
    return chart;
  }
示例#19
0
  public static void main(String[] args) {

    /** Getting time series */
    TimeSeries series = CsvTicksLoader.loadAppleIncSeries();

    /** Creating indicators */
    // Close price
    ClosePriceIndicator closePrice = new ClosePriceIndicator(series);
    // Bollinger bands
    BollingerBandsMiddleIndicator middleBBand = new BollingerBandsMiddleIndicator(closePrice);
    BollingerBandsLowerIndicator lowBBand =
        new BollingerBandsLowerIndicator(middleBBand, closePrice);
    BollingerBandsUpperIndicator upBBand =
        new BollingerBandsUpperIndicator(middleBBand, closePrice);

    /** Building chart dataset */
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(buildChartTimeSeries(series, closePrice, "Apple Inc. (AAPL) - NASDAQ GS"));
    dataset.addSeries(buildChartTimeSeries(series, lowBBand, "Low Bollinger Band"));
    dataset.addSeries(buildChartTimeSeries(series, upBBand, "High Bollinger Band"));

    /** Creating the chart */
    JFreeChart chart =
        ChartFactory.createTimeSeriesChart(
            "Apple Inc. 2013 Close Prices", // title
            "Date", // x-axis label
            "Price Per Unit", // y-axis label
            dataset, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
            );
    XYPlot plot = (XYPlot) chart.getPlot();
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));

    /** Displaying the chart */
    displayChart(chart);
  }
  /**
   * Creates a sample chart.
   *
   * @param dataset the dataset for the chart.
   * @return a sample chart.
   */
  private static JFreeChart createChart(TableXYDataset dataset) {

    DateAxis domainAxis = new DateAxis("Year");
    domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
    domainAxis.setLowerMargin(0.01);
    domainAxis.setUpperMargin(0.01);

    NumberAxis rangeAxis = new NumberAxis("Tonnes");
    // rangeAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
    rangeAxis.setNumberFormatOverride(new DecimalFormat("0.0%"));
    StackedXYBarRenderer renderer = new StackedXYBarRenderer(0.30);
    renderer.setRenderAsPercentages(true);
    renderer.setDrawBarOutline(false);

    renderer.setBaseToolTipGenerator(
        new StandardXYToolTipGenerator(
            "{0} : {1} = {2} tonnes", new SimpleDateFormat("yyyy"), new DecimalFormat("#,##0")));

    XYPlot plot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    JFreeChart chart = new JFreeChart("Waste Management", plot);
    chart.setBackgroundPaint(Color.white);
    chart.addSubtitle(new TextTitle("St Albans City and District Council"));

    ChartUtilities.applyCurrentTheme(chart);

    GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, new Color(64, 0, 0), 0.0f, 0.0f, Color.red);
    GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, new Color(0, 64, 0), 0.0f, 0.0f, Color.green);
    renderer.setSeriesPaint(0, gp0);
    renderer.setSeriesPaint(1, gp1);
    renderer.setGradientPaintTransformer(
        new StandardGradientPaintTransformer(GradientPaintTransformType.HORIZONTAL));

    return chart;
  }
    public PrecisionErrorChart() {
      super(new BorderLayout());
      timeseriescollectionPrecisionError = new TimeSeriesCollection();

      DateAxis dateaxis = new DateAxis("Time (hh:mm:ss)");
      dateaxis.setTickLabelFont(new Font("SansSerif", 0, 12));
      dateaxis.setLabelFont(new Font("SansSerif", 0, 14));
      dateaxis.setAutoRange(true);
      dateaxis.setUpperMargin(0.3D);
      dateaxis.setTickLabelsVisible(true);

      NumberAxis numberaxis = new NumberAxis("Precision error (ms)");
      numberaxis.setTickLabelFont(new Font("SansSerif", 0, 12));
      numberaxis.setLabelFont(new Font("SansSerif", 0, 14));
      numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
      numberaxis.setRangeWithMargins(-100.0, 100.0);

      XYLineAndShapeRenderer xylineandshaperenderer = new XYLineAndShapeRenderer(true, false);
      xylineandshaperenderer.setSeriesPaint(0, Color.blue);
      xylineandshaperenderer.setSeriesPaint(1, Color.red);
      xylineandshaperenderer.setSeriesPaint(2, Color.green);
      xylineandshaperenderer.setSeriesPaint(3, Color.pink);
      xylineandshaperenderer.setSeriesPaint(4, Color.magenta);
      xylineandshaperenderer.setSeriesPaint(5, Color.cyan);
      xylineandshaperenderer.setSeriesStroke(0, new BasicStroke(0.7F, 0, 2));
      xylineandshaperenderer.setSeriesStroke(1, new BasicStroke(0.7F, 0, 2));
      xylineandshaperenderer.setBaseShapesVisible(true);

      XYPlot xyplot =
          new XYPlot(
              timeseriescollectionPrecisionError, dateaxis, numberaxis, xylineandshaperenderer);
      xyplot.setBackgroundPaint(Color.lightGray);
      xyplot.setDomainGridlinePaint(Color.white);
      xyplot.setRangeGridlinePaint(Color.white);
      xyplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
      xyplot.setDomainGridlinesVisible(true);

      JFreeChart jfreechart =
          new JFreeChart("Time Precision Error", new Font("SansSerif", 1, 24), xyplot, true);
      jfreechart.setBackgroundPaint(Color.white);
      ChartPanel chartpanel = new ChartPanel(jfreechart, true);
      add(chartpanel);
    }
示例#22
0
  public JFreeChart makegraph(Second g_start, Second g_end) {
    // used
    XYDataset xydataset1 = this.createused();
    XYPlot subplot1;
    NumberAxis usedaxis = new NumberAxis("% used cpu");
    if (mysar.show100axiscpu) {
      usedaxis.setRange(0.0D, 100D);
    }

    if (mysar.showstackedcpu) {
      StackedXYAreaRenderer2 renderer = new StackedXYAreaRenderer2();
      renderer.setSeriesPaint(0, kSarConfig.color1);
      renderer.setSeriesPaint(1, kSarConfig.color2);
      renderer.setSeriesPaint(2, kSarConfig.color3);
      renderer.setSeriesPaint(3, kSarConfig.color4);
      subplot1 = new XYPlot(stacked_used, new DateAxis(null), usedaxis, renderer);

    } else {
      XYItemRenderer minichart1 = new StandardXYItemRenderer();
      minichart1.setBaseStroke(kSarConfig.DEFAULT_STROKE);
      minichart1.setSeriesPaint(0, kSarConfig.color1);
      minichart1.setSeriesPaint(1, kSarConfig.color2);
      minichart1.setSeriesPaint(2, kSarConfig.color3);
      minichart1.setSeriesPaint(2, kSarConfig.color4);
      subplot1 = new XYPlot(xydataset1, null, usedaxis, minichart1);
    }
    // idle
    XYDataset idleset = this.createidle();
    XYItemRenderer minichart2 = new StandardXYItemRenderer();
    minichart2.setSeriesPaint(0, kSarConfig.color5);
    minichart2.setBaseStroke(kSarConfig.DEFAULT_STROKE);
    XYPlot subplot2 = new XYPlot(idleset, null, new NumberAxis("% idle"), minichart2);
    // nice
    XYDataset niceset = this.createnice();
    XYItemRenderer minichart3 = new StandardXYItemRenderer();
    minichart3.setSeriesPaint(0, kSarConfig.color6);
    minichart3.setBaseStroke(kSarConfig.DEFAULT_STROKE);
    XYPlot subplot3 = new XYPlot(niceset, null, new NumberAxis("% niced"), minichart3);

    // the graph
    CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis(""));
    plot.add(subplot1, 2);
    plot.add(subplot3, 1);
    plot.add(subplot2, 1);
    plot.setOrientation(PlotOrientation.VERTICAL);
    // the graph
    JFreeChart mychart = new JFreeChart(this.getGraphTitle(), kSarConfig.DEFAULT_FONT, plot, true);
    if (g_start != null) {
      DateAxis dateaxis1 = (DateAxis) mychart.getXYPlot().getDomainAxis();
      dateaxis1.setRange(g_start.getStart(), g_end.getEnd());
    }
    if (setbackgroundimage(mychart) == 1) {
      subplot1.setBackgroundPaint(null);
      subplot2.setBackgroundPaint(null);
      subplot3.setBackgroundPaint(null);
    }

    // idle trigger
    cpuidletrigger.setTriggerValue(kSarConfig.linuxcpuidletrigger);
    cpuidletrigger.tagMarker(subplot2);
    // system trigger
    cpusystemtrigger.setTriggerValue(kSarConfig.linuxcpusystemtrigger);
    cpusystemtrigger.tagMarker(subplot1);
    // wio trigger
    if (cpuOpt.equals("%iowait") || cpuOpt.equals("%steal")) {
      cpuwiotrigger.setTriggerValue(kSarConfig.linuxcpuwiotrigger);
      cpuwiotrigger.tagMarker(subplot1);
    }
    // usr trigger
    cpuusrtrigger.setTriggerValue(kSarConfig.linuxcpuusrtrigger);
    cpuusrtrigger.tagMarker(subplot1);
    //
    return mychart;
  }
  public static JFreeChart createChartZhu(IntervalXYDataset dataset) {

    JFreeChart chart =
        ChartFactory.createXYBarChart(
            "时间段内车辆出入统计柱形图", // title
            "数据日期从" + min + "到" + max,
            true, // x-axis label
            "车辆出入数量", // y-axis label
            dataset,
            PlotOrientation.VERTICAL, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
            );
    chart.setBackgroundPaint(Color.white);
    chart.getTitle().setFont(new Font("宋体", Font.BOLD, 15));
    // chart.getCategoryPlot().getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    XYPlot plot2 = (XYPlot) chart.getPlot();
    plot2.setBackgroundPaint(Color.lightGray);
    plot2.setDomainGridlinePaint(Color.white);
    plot2.setRangeGridlinePaint(Color.white);
    plot2.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); // 设定坐标轴与图表数据显示部分距离
    plot2.setDomainCrosshairVisible(true);
    plot2.setRangeCrosshairVisible(true);
    plot2.getRangeAxis().setLabelFont(new Font("宋体", Font.BOLD, 15));
    // 横轴框里的标题字体
    chart.getLegend().setItemFont(new Font("宋体", Font.ITALIC, 10));
    // 横轴列表字体
    plot2.getDomainAxis().setTickLabelFont(new Font("新宋体", 1, 10));
    // 横轴小标题字体
    plot2.getDomainAxis().setLabelFont(new Font("新宋体", 1, 10));
    plot2.setNoDataMessage("没有数据");
    plot2.setBackgroundAlpha(0.5f);

    XYBarRenderer xyBarRender = new XYBarRenderer();
    xyBarRender.setMargin(0.5); // 设置柱形图之间的间隔

    GradientPaint gradientpaint1 =
        new GradientPaint(0.0F, 0.0F, Color.black, 0.0F, 0.0F, new Color(0, 0, 64));
    GradientPaint gradientpaint3 =
        new GradientPaint(0.0F, 0.0F, Color.red, 0.0F, 0.0F, new Color(64, 0, 0));

    xyBarRender.setSeriesPaint(0, gradientpaint1);
    xyBarRender.setSeriesPaint(1, gradientpaint3);
    xyBarRender.setSeriesVisibleInLegend(1, true, true);
    xyBarRender.setBarAlignmentFactor(0.5);
    xyBarRender.setDrawBarOutline(false);

    xyBarRender.setSeriesStroke(
        0,
        new BasicStroke(
            2.0f,
            BasicStroke.CAP_ROUND,
            BasicStroke.JOIN_ROUND,
            1.0f,
            new float[] {10.0f, 6.0f},
            0.0f));
    xyBarRender.setSeriesStroke(
        1,
        new BasicStroke(
            5.0f,
            BasicStroke.CAP_SQUARE,
            BasicStroke.JOIN_ROUND,
            5.0f,
            new float[] {15.0f, 10.0f},
            10.0f));

    plot2.setRenderer(xyBarRender);
    ClusteredXYBarRenderer clusteredxybarrenderer = new ClusteredXYBarRenderer(0.001D, false);
    plot2.setRenderer(clusteredxybarrenderer);

    // CategoryAxis横抽,通过getDomainAxis取得,NumberAxis纵轴,通过getRangeAxis取得。
    DateAxis axis = (DateAxis) plot2.getDomainAxis();
    // axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));
    if (type == 0) // type = 0则以1天为横轴最小坐标,为1则以1月为横轴最小坐标
    {
      axis.setDateFormatOverride(new SimpleDateFormat("dd")); // 设置时间格式
      axis.setTickUnit(new DateTickUnit(DateTickUnit.DAY, 1));
    } else {
      axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM"));
      axis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH, 1));
    }
    axis.setLabelFont(new Font("黑体", Font.TRUETYPE_FONT, 12));
    // axis.setLabelAngle(0.85);
    axis.setAutoTickUnitSelection(false); // 时间轴的数据标签是否自动确
    // ItemLabelPosition itemlabelposition = new
    // ItemLabelPosition(ItemLabelAnchor.INSIDE12,TextAnchor.CENTER_RIGHT,TextAnchor.CENTER_RIGHT,
    // -1.57D);

    // 下面这一块是用来设置轴的时间间隔的,可能会出现,出错时可以简单设处日期就行了
    // 设置X轴间隔的另一种方法更好不出错
    int a = 1;
    a = (int) (daycount / 10) + 1;
    // axis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,a));
    // axis.setLabelAngle(0.45);
    // axis.setLabelInsets(, true);

    NumberAxis numberaxis = (NumberAxis) plot2.getRangeAxis();
    numberaxis.setAxisLineVisible(false); // 是否显示纵坐标
    numberaxis.setTickMarksVisible(false); // 是否显示坐标标尺
    numberaxis.setAutoRangeIncludesZero(false); // 是否自动包含0起点? 默认为true
    numberaxis.setAutoTickUnitSelection(false); // 数据轴的数据标签是否自动确定
    int space_y = (int) ((highValue_Y * 1.1 - minValue_Y * 0.9) / 10);
    if (space_y == 0) space_y = 1;
    System.out.println("spacespace sapce space" + space_y);
    numberaxis.setTickUnit(new NumberTickUnit(space_y)); // 设置刻度显示的密度
    numberaxis.setAutoRangeMinimumSize(2D);
    return chart;
  }
示例#24
0
  private ChartPanel getChartPanel(DefaultXYZDataset dataset, int i) {
    String key = (String) dataset.getSeriesKey(0);
    DateAxis yAxis = new DateAxis("Date");
    yAxis.setLowerMargin(0.0);
    yAxis.setUpperMargin(0.0);
    yAxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY, 1));

    NumberAxis xAxis = new NumberAxis("Hour");
    xAxis.setUpperMargin(0.0);
    xAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    XYBlockRenderer renderer = new XYBlockRenderer();
    renderer.setBlockWidth(1000.0 * 60.0 * 60.0 * 24.0);
    renderer.setBlockAnchor(RectangleAnchor.BOTTOM_LEFT);

    // range scaling
    PaintScale paintScale;
    if (colorSort.getValue().equals("gray")) // gray scaling
    {
      paintScale = new GrayPaintScale(0.0, maxArray[i]);
    } else {

      int color_max, color_min;
      if (colorSort.getValue().equals("red")) { // red scaling
        color_max = 0xFF33FF;
        color_min = 0xFF3300;
      } else if (colorSort.getValue().equals("blue")) { // blue scaling
        color_max = 0x0033FF;
        color_min = 0x003300;
      } else { // yellow scaling
        color_max = 0xFFFFFF;
        color_min = 0xFFFF00;
      }
      paintScale = new LookupPaintScale(0.0, maxArray[i], new Color(color_max));
      int d = Math.max((color_max - color_min) / ((int) maxArray[i] + 1), 1);
      for (int k = 0; k <= maxArray[i]; k++) {
        ((LookupPaintScale) paintScale)
            .add(new Double(k + 0.5), new Color(color_max - (k + 1) * d));
      }
    }
    renderer.setPaintScale(paintScale);

    XYPlot plot = new XYPlot(dataset, yAxis, xAxis, renderer);
    plot.setOrientation(PlotOrientation.HORIZONTAL);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setForegroundAlpha(0.66F);
    JFreeChart chart = new JFreeChart(key, plot);
    chart.removeLegend();
    chart.setBackgroundPaint(Color.white);

    // adding data ranges
    NumberAxis scaleAxis = new NumberAxis(null);
    scaleAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    scaleAxis.setLowerBound(0.0);
    scaleAxis.setUpperBound(maxArray[i]);
    PaintScaleLegend psl = new PaintScaleLegend(paintScale, scaleAxis);
    psl.setAxisOffset(5.0);
    psl.setPosition(RectangleEdge.BOTTOM);
    psl.setMargin(new RectangleInsets(5, 5, 5, 5));
    chart.addSubtitle(psl);

    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setBorder(BorderFactory.createLineBorder(Color.lightGray));
    return chartPanel;
  }
示例#25
0
  private File createPNG(
      String streamName,
      int width,
      int height,
      String outputPath,
      boolean isLine,
      boolean isShape) {

    StreamDatabaseDriver db = null;
    String requestingUser = owner;
    String streamOwner = owner;

    String startTime = fmt.print(startDate);
    String endTime = fmt.print(endDate);

    try {
      db = DatabaseConnector.getStreamDatabase();

      boolean isData =
          db.prepareQuery(
              requestingUser,
              streamOwner,
              streamName,
              startTime,
              endTime,
              null,
              null,
              0,
              0,
              0,
              true,
              null);
      Stream stream = db.getStoredStreamInfo();

      if (!isData) {
        Log.error("isData null");
        return null;
      }

      if (stream.num_samples > width) {
        db.close();
        db = DatabaseConnector.getStreamDatabase();
        int skipEveryNth = (int) (stream.num_samples / width);
        isData =
            db.prepareQuery(
                requestingUser,
                streamOwner,
                streamName,
                startTime,
                endTime,
                null,
                null,
                0,
                0,
                skipEveryNth,
                false,
                null);
        stream = db.getStoredStreamInfo();

        if (!isData) {
          Log.error("isData null");
          return null;
        }
      }

      // Prepare data
      XYSeries[] series = null;
      long minTsInterval = Long.MAX_VALUE; // to determine whether to use marker on the plot.
      long prevTimestamp = -1;
      Object[] tuple = new Object[db.getStoredStreamInfo().channels.size() + 1];
      while (db.getNextTuple(tuple)) {
        // Init XYSeries array
        if (series == null) {
          series = new XYSeries[tuple.length - 1];
          for (int i = 0; i < series.length; i++) {
            series[i] = new XYSeries(stream.channels.get(i).name);
          }
        }

        long timestamp = ((Long) tuple[0]).longValue();
        for (int i = 1; i < tuple.length; i++) {
          try {
            series[i - 1].add(timestamp, (Number) tuple[i]);
          } catch (ClassCastException e) {
            continue;
          }
        }

        long diff = timestamp - prevTimestamp;
        if (diff > 0 && diff < minTsInterval) {
          minTsInterval = diff;
        }

        prevTimestamp = timestamp;
      }

      db.close();
      db = null;

      if (series == null) {
        throw new UnsupportedOperationException("No data for " + streamName);
      }

      XYSeriesCollection xyDataset = new XYSeriesCollection();
      for (XYSeries s : series) {
        xyDataset.addSeries(s);
      }

      // Generate title string
      long start = (long) series[0].getMinX();
      long end = (long) series[0].getMaxX();
      Timestamp startTimestamp = new Timestamp(start);
      Timestamp endTimestamp = new Timestamp(end);
      String title =
          stream.owner
              + ": "
              + stream.name
              + "\n"
              + startTimestamp.toString()
              + " ~ "
              + endTimestamp.toString();

      //  Create the chart object
      DateAxis xAxis = new DateAxis("Time");
      xAxis.setDateFormatOverride(new SimpleDateFormat("hh:mm aa"));
      // NumberAxis xAxis = new NumberAxis("");
      long margin = (endDate.getMillis() - startDate.getMillis()) / 24;
      xAxis.setRange(
          new Date(startDate.getMillis() - margin), new Date(endDate.getMillis() + margin));

      NumberAxis yAxis = new NumberAxis("Value");
      yAxis.setAutoRangeIncludesZero(false); // override default

      if (streamName.equals(ACTIVITY_SENSOR)) {
        yAxis.setTickUnit(new NumberTickUnit(1.0));
        yAxis.setRange(0.0, 4.0);
      } else if (streamName.equals(STRESS_SENSOR)) {
        yAxis.setTickUnit(new NumberTickUnit(1.0));
        yAxis.setRange(0.0, 1.0);
      } else if (streamName.equals(CONVERSATION_SENSOR)) {
        yAxis.setTickUnit(new NumberTickUnit(1.0));
        yAxis.setRange(0.0, 2.0);
      }

      StandardXYItemRenderer renderer;
      // long dataCount = (end - start) / minTsInterval;
      // if (dataCount <= width) {
      //	renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES +
      // StandardXYItemRenderer.SHAPES);
      // } else {
      //	renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES);
      // }
      if (isLine && isShape) {
        renderer =
            new StandardXYItemRenderer(
                StandardXYItemRenderer.LINES + StandardXYItemRenderer.SHAPES);
      } else if (isLine && !isShape) {
        renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES);
      } else if (!isLine && isShape) {
        renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES);
      } else {
        renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES);
      }
      // renderer.setShapesFilled(true);

      XYPlot plot = new XYPlot(xyDataset, xAxis, yAxis, renderer);
      JFreeChart chart =
          new JFreeChart(title, new Font(Font.SANS_SERIF, Font.BOLD, 12), plot, true);
      // JFreeChart chart = new JFreeChart(title, plot);
      chart.setBackgroundPaint(java.awt.Color.WHITE);
      chart.removeLegend();

      // Marker
      final Color c = new Color(255, 60, 24, 63);
      List<Range> markerRanges = getUnsharedRanges(streamOwner, streamName);

      for (Range range : markerRanges) {
        Marker marker =
            new IntervalMarker(
                range.startTimeInMillis,
                range.endTimeInMillis,
                c,
                new BasicStroke(2.0f),
                null,
                null,
                1.0f);
        plot.addDomainMarker(marker, Layer.BACKGROUND);
      }

      ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      String filename = ServletUtilities.saveChartAsPNG(chart, width, height, info, null);

      File imageFile = new File("/tmp/" + filename);
      File toFile =
          new File(outputPath + "/" + streamName + "_" + fileFmt.print(startDate) + ".png");
      imageFile.renameTo(toFile);

      return toFile;

    } catch (ClassNotFoundException
        | IOException
        | NamingException
        | SQLException
        | UnsupportedOperationException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
    return null;
  }
  private JFreeChart createChart() {

    // create the chart...
    JFreeChart chart =
        ChartFactory.createXYLineChart(
            null, // chart title
            null, // x axis label
            null, // y axis label
            null, // data
            PlotOrientation.VERTICAL,
            false, // include legend
            true, // tooltips
            false // urls
            );

    chart.setBackgroundPaint(Color.white);

    // get a reference to the plot for further customization...
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // domain axis

    if ((indexAxis >= 0) && (!dataTable.isNominal(indexAxis))) {
      if ((dataTable.isDate(indexAxis)) || (dataTable.isDateTime(indexAxis))) {
        DateAxis domainAxis = new DateAxis(dataTable.getColumnName(indexAxis));
        domainAxis.setTimeZone(Tools.getPreferredTimeZone());
        chart.getXYPlot().setDomainAxis(domainAxis);
      }
    } else {
      plot.getDomainAxis().setStandardTickUnits(NumberAxis.createIntegerTickUnits(Locale.US));
      ((NumberAxis) plot.getDomainAxis()).setAutoRangeStickyZero(false);
      ((NumberAxis) plot.getDomainAxis()).setAutoRangeIncludesZero(false);
    }
    ValueAxis xAxis = plot.getDomainAxis();
    if (indexAxis > -1) xAxis.setLabel(getDataTable().getColumnName(indexAxis));
    else xAxis.setLabel(SERIESINDEX_LABEL);
    xAxis.setAutoRange(true);
    xAxis.setLabelFont(LABEL_FONT_BOLD);
    xAxis.setTickLabelFont(LABEL_FONT);
    xAxis.setVerticalTickLabels(isLabelRotating());
    if (indexAxis > 0) {
      if (getRangeForDimension(indexAxis) != null) {
        xAxis.setRange(getRangeForDimension(indexAxis));
      }
    } else {
      if (getRangeForName(SERIESINDEX_LABEL) != null) {
        xAxis.setRange(getRangeForName(SERIESINDEX_LABEL));
      }
    }

    // renderer and range axis
    synchronized (dataTable) {
      int numberOfSelectedColumns = 0;
      for (int c = 0; c < dataTable.getNumberOfColumns(); c++) {
        if (getPlotColumn(c)) {
          if (dataTable.isNumerical(c)) {
            numberOfSelectedColumns++;
          }
        }
      }

      int columnCount = 0;
      for (int c = 0; c < dataTable.getNumberOfColumns(); c++) {
        if (getPlotColumn(c)) {
          if (dataTable.isNumerical(c)) {
            // YIntervalSeries series = new YIntervalSeries(this.dataTable.getColumnName(c));
            XYSeriesCollection dataset = new XYSeriesCollection();
            XYSeries series = new XYSeries(dataTable.getColumnName(c));
            Iterator<DataTableRow> i = dataTable.iterator();
            int index = 1;
            while (i.hasNext()) {
              DataTableRow row = i.next();
              double value = row.getValue(c);

              if ((indexAxis >= 0) && (!dataTable.isNominal(indexAxis))) {
                double indexValue = row.getValue(indexAxis);
                series.add(indexValue, value);
              } else {
                series.add(index++, value);
              }
            }
            dataset.addSeries(series);

            XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();

            Color color = getColorProvider().getPointColor(1.0d);
            if (numberOfSelectedColumns > 1) {
              color =
                  getColorProvider()
                      .getPointColor(columnCount / (double) (numberOfSelectedColumns - 1));
            }
            renderer.setSeriesPaint(0, color);
            renderer.setSeriesStroke(
                0, new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
            renderer.setSeriesShapesVisible(0, false);

            NumberAxis yAxis = new NumberAxis(dataTable.getColumnName(c));
            if (getRangeForDimension(c) != null) {
              yAxis.setRange(getRangeForDimension(c));
            } else {
              yAxis.setAutoRange(true);
              yAxis.setAutoRangeStickyZero(false);
              yAxis.setAutoRangeIncludesZero(false);
            }
            yAxis.setLabelFont(LABEL_FONT_BOLD);
            yAxis.setTickLabelFont(LABEL_FONT);
            if (numberOfSelectedColumns > 1) {
              yAxis.setAxisLinePaint(color);
              yAxis.setTickMarkPaint(color);
              yAxis.setLabelPaint(color);
              yAxis.setTickLabelPaint(color);
            }

            plot.setRangeAxis(columnCount, yAxis);
            plot.setRangeAxisLocation(columnCount, AxisLocation.TOP_OR_LEFT);

            plot.setDataset(columnCount, dataset);
            plot.setRenderer(columnCount, renderer);
            plot.mapDatasetToRangeAxis(columnCount, columnCount);

            columnCount++;
          }
        }
      }
    }

    chart.setBackgroundPaint(Color.white);

    return chart;
  }
  public String generateXYAreaChart(
      HttpSession session, PrintWriter pw, String courseId, int studentId) {
    String filename = null;
    /* int groupId=0;
    if (groupName.equals("All")){
        groupId=0;
    }else{
         groupId = studStatisticBean.getGroupIdByName(groupName);
    }*/

    try {
      //  Retrieve list of WebHits for each section and populate a TableXYDataset
      StudentsConceptChartDataSet cDataSet =
          new StudentsConceptChartDataSet(studStatisticBean, courseId, studentId);
      // cDataSet.setStudentStatisticBeanIdRef(studStatisticBean);
      ArrayList sections = cDataSet.getSections();
      Iterator sectionIter = sections.iterator();
      DefaultTableXYDataset dataset = new DefaultTableXYDataset();
      while (sectionIter.hasNext()) {
        String section = (String) sectionIter.next();
        ArrayList list = cDataSet.getDataByHitConcept(section);
        XYSeries dataSeries = new XYSeries(section, true, false);
        Iterator webHitIter = list.iterator();
        while (webHitIter.hasNext()) {
          StudentsConceptHit cHit = (StudentsConceptHit) webHitIter.next();
          dataSeries.add(cHit.getOrdNumb(), cHit.getHitDegree());
        }
        dataset.addSeries(dataSeries);
      }

      //  Throw a custom NoDataException if there is no data
      if (dataset.getItemCount() == 0) {
        System.out.println("No data has been found");
        throw new NoDataException();
      }

      //  Create tooltip and URL generators
      SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.UK);
      StandardXYToolTipGenerator ttg =
          new StandardXYToolTipGenerator(
              StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, sdf, NumberFormat.getInstance());
      TimeSeriesURLGenerator urlg =
          new TimeSeriesURLGenerator(sdf, "bar_chart.jsp", "series", "hitDate");

      //  Create the X-Axis
      DateAxis xAxis = new DateAxis(null);
      xAxis.setLowerMargin(0.0);
      xAxis.setUpperMargin(0.0);

      //  Create the X-Axis
      NumberAxis yAxis = new NumberAxis(null);
      yAxis.setAutoRangeIncludesZero(true);

      //  Create the renderer
      StackedXYAreaRenderer renderer =
          new StackedXYAreaRenderer(XYAreaRenderer.AREA_AND_SHAPES, ttg, urlg);
      renderer.setSeriesPaint(0, new Color(255, 255, 180));
      renderer.setSeriesPaint(1, new Color(206, 230, 255));
      renderer.setSeriesPaint(2, new Color(255, 230, 230));
      renderer.setSeriesPaint(3, new Color(206, 255, 206));
      renderer.setShapePaint(Color.gray);
      renderer.setShapeStroke(new BasicStroke(0.5f));
      renderer.setShape(new Ellipse2D.Double(-3, -3, 6, 6));
      renderer.setOutline(true);

      //  Create the plot
      XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
      plot.setForegroundAlpha(0.65f);

      //  Reconfigure Y-Axis so the auto-range knows that the data is stacked
      yAxis.configure();

      //  Create the chart
      JFreeChart chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
      chart.setBackgroundPaint(java.awt.Color.white);

      //  Write the chart image to the temporary directory
      ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      filename = ServletUtilities.saveChartAsPNG(chart, 600, 400, info, session);

      //  Write the image map to the PrintWriter
      ChartUtilities.writeImageMap(pw, filename, info);
      pw.flush();

    } catch (NoDataException e) {
      System.out.println(e.toString());
      filename = "public_nodata_500x300.png";
    } catch (Exception e) {
      System.out.println("Exception - " + e.toString());
      e.printStackTrace(System.out);
      filename = "public_error_500x300.png";
    }
    return filename;
  }
示例#28
0
  /**
   * Creates an overlaid chart.
   *
   * @return The chart.
   */
  private static JFreeChart createCombinedChart() {

    // create plot ...
    IntervalXYDataset data1 = createDataset1();
    XYItemRenderer renderer1 = new XYLineAndShapeRenderer(true, false);
    renderer1.setBaseToolTipGenerator(
        new StandardXYToolTipGenerator(
            StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
            new SimpleDateFormat("d-MMM-yyyy"),
            new DecimalFormat("0.00")));
    renderer1.setSeriesStroke(
        0, new BasicStroke(4.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer1.setSeriesPaint(0, Color.blue);

    DateAxis domainAxis = new DateAxis("Year");
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.02);
    ValueAxis rangeAxis = new NumberAxis("$billion");
    XYPlot plot1 = new XYPlot(data1, null, rangeAxis, renderer1);
    plot1.setBackgroundPaint(Color.lightGray);
    plot1.setDomainGridlinePaint(Color.white);
    plot1.setRangeGridlinePaint(Color.white);

    // add a second dataset and renderer...
    IntervalXYDataset data2 = createDataset2();
    XYBarRenderer renderer2 =
        new XYBarRenderer() {
          public Paint getItemPaint(int series, int item) {
            XYDataset dataset = getPlot().getDataset();
            if (dataset.getYValue(series, item) >= 0.0) {
              return Color.red;
            } else {
              return Color.green;
            }
          }
        };
    renderer2.setSeriesPaint(0, Color.red);
    renderer2.setDrawBarOutline(false);
    renderer2.setBaseToolTipGenerator(
        new StandardXYToolTipGenerator(
            StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
            new SimpleDateFormat("d-MMM-yyyy"),
            new DecimalFormat("0.00")));

    XYPlot plot2 = new XYPlot(data2, null, new NumberAxis("$billion"), renderer2);
    plot2.setBackgroundPaint(Color.lightGray);
    plot2.setDomainGridlinePaint(Color.white);
    plot2.setRangeGridlinePaint(Color.white);

    CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(domainAxis);
    cplot.add(plot1, 3);
    cplot.add(plot2, 2);
    cplot.setGap(8.0);
    cplot.setDomainGridlinePaint(Color.white);
    cplot.setDomainGridlinesVisible(true);
    cplot.setDomainPannable(true);

    // return a new chart containing the overlaid plot...
    JFreeChart chart =
        new JFreeChart("United States Public Debt", JFreeChart.DEFAULT_TITLE_FONT, cplot, false);
    TextTitle source =
        new TextTitle(
            "Source: http://www.publicdebt.treas.gov/opd/opdhisms.htm",
            new Font("Dialog", Font.PLAIN, 10));
    source.setPosition(RectangleEdge.BOTTOM);
    source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
    chart.addSubtitle(source);
    LegendTitle legend = new LegendTitle(cplot);
    chart.addSubtitle(legend);
    ChartUtilities.applyCurrentTheme(chart);
    renderer2.setBarPainter(new StandardXYBarPainter());
    renderer2.setShadowVisible(false);
    return chart;
  }
示例#29
0
  static JFreeChart createChart(
      NavigableMap<TimeAxisKey, DiffStat> aggregatedDiffstats,
      DiffStatConfiguration configuration) {

    boolean legend = false;
    boolean tooltips = false;
    boolean urls = false;
    Font helvetica = new Font("Helvetica", Font.PLAIN, 11 * configuration.multiplierInt());

    XYDatasetMinMax datasetMinMax =
        createDeltaDataset("Additions and Delections", aggregatedDiffstats);
    XYDataset dataset = datasetMinMax.dataset;
    JFreeChart chart =
        ChartFactory.createTimeSeriesChart("", "", "", dataset, legend, tooltips, urls);

    chart.setBackgroundPaint(WHITE);
    chart.setBorderVisible(false);

    float strokeWidth = 1.2f * configuration.multiplierFloat();

    XYPlot plot = chart.getXYPlot();
    plot.setOrientation(VERTICAL);
    plot.setBackgroundPaint(WHITE);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(AXIS_LINE_COLOR);
    plot.setDomainGridlineStroke(new BasicStroke(1.0f * configuration.multiplierFloat()));
    plot.setRangeGridlinesVisible(false);

    plot.setOutlineVisible(false);

    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setDateFormatOverride(new SimpleDateFormat("MM/yy"));
    dateAxis.setTickLabelFont(helvetica);
    dateAxis.setAxisLineVisible(false);
    dateAxis.setTickUnit(computeDateTickUnit(aggregatedDiffstats));
    RectangleInsets insets =
        new RectangleInsets(
            8.0d * configuration.multiplierDouble(),
            4.0d * configuration.multiplierDouble(),
            4.0d * configuration.multiplierDouble(),
            4.0d * configuration.multiplierDouble());
    dateAxis.setTickLabelInsets(insets);

    NumberAxis additionDeletionAxis = (NumberAxis) plot.getRangeAxis(0);
    additionDeletionAxis.setAxisLineVisible(false);
    additionDeletionAxis.setLabel("Additions and Deletions");
    additionDeletionAxis.setLabelFont(helvetica);
    additionDeletionAxis.setTickLabelFont(helvetica);
    additionDeletionAxis.setRangeType(RangeType.FULL);
    int lowerBound = datasetMinMax.min + (int) (datasetMinMax.min * 0.1d);
    additionDeletionAxis.setLowerBound(lowerBound);
    int upperBound = datasetMinMax.max + (int) (datasetMinMax.max * 0.1d);
    additionDeletionAxis.setUpperBound(upperBound);
    additionDeletionAxis.setNumberFormatOverride(new AbbreviatingNumberFormat());
    additionDeletionAxis.setMinorTickMarksVisible(false);
    additionDeletionAxis.setTickMarkInsideLength(5.0f * configuration.multiplierFloat());
    additionDeletionAxis.setTickMarkOutsideLength(0.0f);
    additionDeletionAxis.setTickMarkStroke(new BasicStroke(2.0f * configuration.multiplierFloat()));
    additionDeletionAxis.setTickUnit(
        new NumberTickUnit(computeTickUnitSize(datasetMinMax.max + abs(datasetMinMax.min))));

    XYAreaRenderer areaRenderer = new XYAreaRenderer(XYAreaRenderer.AREA);
    areaRenderer.setOutline(true);
    areaRenderer.setSeriesOutlinePaint(0, ADDED_STROKE);
    areaRenderer.setSeriesOutlineStroke(0, new BasicStroke(strokeWidth));
    areaRenderer.setSeriesPaint(0, ADDED_FILL);
    areaRenderer.setSeriesOutlinePaint(1, REMOVED_STROKE);
    areaRenderer.setSeriesOutlineStroke(1, new BasicStroke(strokeWidth));
    areaRenderer.setSeriesPaint(1, REMOVED_FILL);
    plot.setRenderer(0, areaRenderer);

    // Total Axis
    NumberAxis totalAxis = new NumberAxis("Total Lines");
    totalAxis.setAxisLineVisible(false);
    totalAxis.setLabelPaint(VALUE_LABEL);
    totalAxis.setTickLabelPaint(TOTAL_LABEL);
    totalAxis.setLabelFont(helvetica);
    totalAxis.setTickLabelFont(helvetica);
    totalAxis.setNumberFormatOverride(new AbbreviatingNumberFormat());
    totalAxis.setMinorTickMarksVisible(false);
    totalAxis.setTickMarkInsideLength(5.0f * configuration.multiplierFloat());
    totalAxis.setTickMarkOutsideLength(0.0f);
    totalAxis.setTickMarkStroke(new BasicStroke(2.0f * configuration.multiplierFloat()));
    totalAxis.setTickMarkPaint(TOTAL_LABEL);
    plot.setRangeAxis(1, totalAxis);
    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);

    XYDatasetAndTotal datasetAndTotal = createTotalDataset("Total Lines", aggregatedDiffstats);
    XYDataset totalDataSet = datasetAndTotal.dataset;
    plot.setDataset(1, totalDataSet);
    plot.mapDatasetToRangeAxis(1, 1);
    //        XYItemRenderer totalRenderer = new XYSplineRenderer();
    XYItemRenderer totalRenderer = new StandardXYItemRenderer();
    totalRenderer.setSeriesPaint(0, TOTAL_FILL);
    totalRenderer.setSeriesStroke(
        0,
        new BasicStroke(
            strokeWidth,
            CAP_ROUND,
            JOIN_ROUND,
            10.0f * configuration.multiplierFloat(),
            new float[] {
              6.0f * configuration.multiplierFloat(), 3.0f * configuration.multiplierFloat()
            },
            0.0f));
    plot.setRenderer(1, totalRenderer);

    totalAxis.setTickUnit(new NumberTickUnit(computeTickUnitSize(datasetAndTotal.total)));

    return chart;
  }