private void scatterPlot(
      Map<Double, Map<String, Tuple<Double, Double>>> inputData, String outFile) {

    String mode1 = travelModes[0];
    String mode2 = travelModes[1];

    XYSeries carFlow = new XYSeries(mode1 + " flow");
    XYSeries bikeFlow = new XYSeries(mode2 + " flow");
    XYSeries carSpeed = new XYSeries(mode1 + " speed");
    XYSeries bikeSpeed = new XYSeries(mode2 + " speed");

    for (double d : inputData.keySet()) {
      carFlow.add(d, inputData.get(d).get(mode1).getFirst());
      carSpeed.add(d, inputData.get(d).get(mode1).getSecond());

      bikeFlow.add(d, inputData.get(d).get(mode2).getFirst());
      bikeSpeed.add(d, inputData.get(d).get(mode2).getSecond());
    }

    // flow vs density
    XYSeriesCollection flowDataset = new XYSeriesCollection();
    flowDataset.addSeries(carFlow);
    flowDataset.addSeries(bikeFlow);

    NumberAxis flowAxis = new NumberAxis("Flow (PCU/h)");
    flowAxis.setRange(0.0, 2100.0);

    XYPlot plot1 = new XYPlot(flowDataset, null, flowAxis, new XYLineAndShapeRenderer(false, true));
    plot1.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);

    // speed vs density
    XYSeriesCollection speedDataset = new XYSeriesCollection();
    speedDataset.addSeries(carSpeed);
    speedDataset.addSeries(bikeSpeed);

    NumberAxis speedAxis = new NumberAxis("Speed (m/s)");
    speedAxis.setRange(0.0, 17.0);

    XYPlot plot2 =
        new XYPlot(speedDataset, null, speedAxis, new XYLineAndShapeRenderer(false, true));
    plot2.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);

    NumberAxis densityAxis = new NumberAxis("Overall density (PCU/km)");
    densityAxis.setRange(0.0, 150.00);

    CombinedDomainXYPlot plot = new CombinedDomainXYPlot(densityAxis);
    plot.setGap(10.);
    plot.add(plot1);
    plot.add(plot2);
    plot.setOrientation(PlotOrientation.VERTICAL);

    JFreeChart chart =
        new JFreeChart("Fundamental diagrams", JFreeChart.DEFAULT_TITLE_FONT, plot, true);

    try {
      ChartUtilities.saveChartAsPNG(new File(outFile), chart, 800, 600);
    } catch (IOException e) {
      throw new RuntimeException("Data is not plotted. Reason " + e);
    }
  }
 private static JFreeChart createChart() {
   XYDataset xydataset = createDirectionDataset(600);
   JFreeChart jfreechart =
       ChartFactory.createTimeSeriesChart(
           "Time", "Date", "Direction", xydataset, true, true, false);
   XYPlot xyplot = (XYPlot) jfreechart.getPlot();
   xyplot.getDomainAxis().setLowerMargin(0.0D);
   xyplot.getDomainAxis().setUpperMargin(0.0D);
   NumberAxis numberaxis = (NumberAxis) xyplot.getRangeAxis();
   numberaxis.setAutoRangeIncludesZero(false);
   TickUnits tickunits = new TickUnits();
   tickunits.add(new NumberTickUnit(180D, new CompassFormat()));
   tickunits.add(new NumberTickUnit(90D, new CompassFormat()));
   tickunits.add(new NumberTickUnit(45D, new CompassFormat()));
   tickunits.add(new NumberTickUnit(22.5D, new CompassFormat()));
   numberaxis.setStandardTickUnits(tickunits);
   xyplot.setRangeAxis(numberaxis);
   XYAreaRenderer xyarearenderer = new XYAreaRenderer();
   NumberAxis numberaxis1 = new NumberAxis("Force");
   numberaxis1.setRange(0.0D, 12D);
   xyarearenderer.setSeriesPaint(0, new Color(0, 0, 255, 128));
   xyplot.setDataset(1, createForceDataset(600));
   xyplot.setRenderer(1, xyarearenderer);
   xyplot.setRangeAxis(1, numberaxis1);
   xyplot.mapDatasetToRangeAxis(1, 1);
   return jfreechart;
 }
Пример #3
0
 /**
  * Sets a new axis range. The period is extended to fit the range size, if necessary.
  *
  * @param range the range.
  * @param turnOffAutoRange switch off the auto range.
  * @param notify notify?
  * @see org.jfree.chart.axis.ValueAxis#setRange(Range, boolean, boolean)
  */
 public void setRange(Range range, boolean turnOffAutoRange, boolean notify) {
   double size = range.getUpperBound() - range.getLowerBound();
   if (size > this.period) {
     this.period = size;
   }
   super.setRange(range, turnOffAutoRange, notify);
 }
 /**
  * Sets the properties of the specified axis to match the properties defined on this panel.
  *
  * @param axis the axis.
  */
 public void setAxisProperties(Axis axis) {
   super.setAxisProperties(axis);
   NumberAxis numberAxis = (NumberAxis) axis;
   numberAxis.setAutoRange(this.autoRange);
   if (!this.autoRange) {
     numberAxis.setRange(this.minimumValue, this.maximumValue);
   }
   //        numberAxis.setGridLinesVisible(this.showGridLinesCheckBox.isSelected());
   //        numberAxis.setGridPaint(this.gridPaintSample.getPaint());
   //        numberAxis.setGridStroke(this.gridStrokeSample.getStroke());
 }
 /**
  * Set the axis range.
  *
  * @param axis a numberAxis
  * @param range a range
  */
 private void setAxisRange(NumberAxis axis, double[] range) {
   if (range == null || range.length != 2) {
     axis.setAutoRange(true);
   } else {
     double lower = range[0];
     double upper = range[1];
     ArgumentNotValid.checkTrue(lower < upper, "Incorrect range");
     axis.setAutoRange(false);
     axis.setRange(new Range(lower, upper));
   }
 }
  private JFreeChart createChart(XYZDataset xyzDataSet) {
    NumberAxis numberAxis = new NumberAxis("X");
    numberAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    numberAxis.setLowerMargin(0.0D);
    numberAxis.setUpperMargin(0.0D);
    numberAxis.setAxisLinePaint(Color.white);
    numberAxis.setTickMarkPaint(Color.white);

    NumberAxis numberAxis1 = new NumberAxis("Y");
    numberAxis1.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    numberAxis1.setLowerMargin(0.0D);
    numberAxis1.setUpperMargin(0.0D);
    numberAxis1.setAxisLinePaint(Color.white);
    numberAxis1.setTickMarkPaint(Color.white);

    XYBlockRenderer xyblockrenderer = new XYBlockRenderer();
    PaintScale paintScale;
    if (this.type == MarkovDataDialog.HeatMapType.COMPARISON)
      paintScale = createNewLookupPaintScale();
    else paintScale = new GrayPaintScale();

    //        paintScale.add(-1.0,Color.WHITE );
    xyblockrenderer.setPaintScale(paintScale);

    XYPlot xyplot = new XYPlot(xyzDataSet, numberAxis, numberAxis1, xyblockrenderer);
    xyplot.setBackgroundPaint(Color.white);
    xyplot.setDomainGridlinesVisible(false);
    xyplot.setRangeGridlinePaint(Color.white);
    xyplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
    xyplot.setOutlinePaint(Color.blue);

    JFreeChart jfreechart = new JFreeChart("heat map", xyplot);
    jfreechart.removeLegend();

    NumberAxis numberAxis2 = new NumberAxis("Scale");
    numberAxis2.setAxisLinePaint(Color.white);
    numberAxis2.setTickMarkPaint(Color.white);
    numberAxis2.setRange(-1.0D, 1.0D);
    numberAxis2.setTickLabelFont(new Font("Dialog", 0, 7));
    PaintScaleLegend paintscalelegend = new PaintScaleLegend(paintScale, numberAxis2);
    paintscalelegend.setStripOutlineVisible(false);
    paintscalelegend.setSubdivisionCount(20);
    paintscalelegend.setAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
    paintscalelegend.setAxisOffset(5D);
    paintscalelegend.setMargin(new RectangleInsets(5D, 5D, 5D, 5D));
    //        paintscalelegend.setFrame(new BlockBorder(Color.red));
    paintscalelegend.setPadding(new RectangleInsets(10D, 10D, 10D, 10D));
    paintscalelegend.setStripWidth(10D);
    paintscalelegend.setPosition(RectangleEdge.LEFT);
    jfreechart.addSubtitle(paintscalelegend);
    //        ChartUtilities.applyCurrentTheme(jfreechart);
    return jfreechart;
  }
Пример #7
0
  /** Some checks for the setLowerBound() method. */
  @Test
  public void testSetLowerBound() {
    NumberAxis axis = new NumberAxis("X");
    axis.setRange(0.0, 10.0);
    axis.setLowerBound(5.0);
    assertEquals(5.0, axis.getLowerBound(), EPSILON);
    axis.setLowerBound(10.0);
    assertEquals(10.0, axis.getLowerBound(), EPSILON);
    assertEquals(11.0, axis.getUpperBound(), EPSILON);

    // axis.setRangeType(RangeType.POSITIVE);
    // axis.setLowerBound(-5.0);
    // assertEquals(0.0, axis.getLowerBound(), EPSILON);
  }
  public void createChart() {

    CategoryDataset categorydataset = (CategoryDataset) this.datasetStrategy.getDataset();
    report =
        ChartFactory.createStackedBarChart(
            this.datasetStrategy.getTitle(),
            this.datasetStrategy.getYAxisLabel(),
            this.datasetStrategy.getXAxisLabel(),
            categorydataset,
            PlotOrientation.HORIZONTAL,
            true,
            true,
            false);
    // report.setBackgroundPaint( Color.lightGray );
    report.setAntiAlias(false);
    report.setPadding(new RectangleInsets(5.0d, 5.0d, 5.0d, 5.0d));
    CategoryPlot categoryplot = (CategoryPlot) report.getPlot();
    categoryplot.setBackgroundPaint(Color.white);
    categoryplot.setRangeGridlinePaint(Color.lightGray);
    NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
    if (datasetStrategy instanceof CloverBarChartStrategy
        || datasetStrategy instanceof MultiCloverBarChartStrategy) {
      numberaxis.setRange(0.0D, StackedBarChartRenderer.NUMBER_AXIS_RANGE);
      numberaxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
    } else {
      numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }
    numberaxis.setLowerMargin(0.0D);
    StackedBarRenderer stackedbarrenderer = (StackedBarRenderer) categoryplot.getRenderer();
    stackedbarrenderer.setDrawBarOutline(false);
    stackedbarrenderer.setItemLabelsVisible(true);
    stackedbarrenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    stackedbarrenderer.setItemLabelFont(
        StackedBarRenderer.DEFAULT_VALUE_LABEL_FONT.deriveFont(Font.BOLD));
    int height =
        (categorydataset.getColumnCount() * ChartUtils.STANDARD_BARCHART_ENTRY_HEIGHT * 2)
            + ChartUtils.STANDARD_BARCHART_ADDITIONAL_HEIGHT
            + 10;
    if (height > ChartUtils.MINIMUM_HEIGHT) {
      super.setHeight(height);
    } else {
      super.setHeight(ChartUtils.MINIMUM_HEIGHT);
    }
    Paint[] paints = this.datasetStrategy.getPaintColor();

    for (int i = 0; i < categorydataset.getRowCount() && i < paints.length; i++) {
      stackedbarrenderer.setSeriesPaint(i, paints[i]);
    }
  }
Пример #9
0
  private JFreeChart createScatChart(
      BufferedImage image, PaintScale ps, int plotWidth, int plotHeigh) {
    JFreeChart chart_temp =
        ChartFactory.createScatterPlot(
            null,
            null,
            null,
            new XYSeriesCollection(),
            PlotOrientation.VERTICAL,
            false,
            false,
            false);
    chart_temp.getXYPlot().getRangeAxis().setInverted(true);
    chart_temp.setBackgroundPaint(JFreeChart.DEFAULT_BACKGROUND_PAINT);
    XYDataImageAnnotation ann = new XYDataImageAnnotation(image, 0, 0, plotWidth, plotHeigh, true);
    XYPlot plot = (XYPlot) chart_temp.getPlot();
    plot.setDomainPannable(true);
    plot.setRangePannable(true);
    plot.getRenderer().addAnnotation(ann, Layer.BACKGROUND);
    NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
    xAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    xAxis.setLowerMargin(0.0);
    xAxis.setUpperMargin(0.0);
    xAxis.setVisible(false);
    NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    yAxis.setLowerMargin(0.0);
    yAxis.setUpperMargin(0.0);
    yAxis.setVisible(false);

    NumberAxis scaleAxis = new NumberAxis();
    scaleAxis.setAxisLinePaint(Color.black);
    scaleAxis.setTickMarkPaint(Color.black);
    scaleAxis.setRange(ps.getLowerBound(), ps.getUpperBound());
    scaleAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 9));
    PaintScaleLegend legend = new PaintScaleLegend(ps, scaleAxis);
    legend.setAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    legend.setMargin(new RectangleInsets(5, 5, 5, 5));
    legend.setStripWidth(10);
    legend.setPosition(RectangleEdge.RIGHT);
    legend.setBackgroundPaint(chart_temp.getBackgroundPaint());
    chart_temp.addSubtitle(legend);

    return chart_temp;
  }
Пример #10
0
 /** Test the translation of Java2D values to data values. */
 public void testTranslateJava2DToValue() {
   NumberAxis axis = new NumberAxis();
   axis.setRange(50.0, 100.0);
   Rectangle2D dataArea = new Rectangle2D.Double(10.0, 50.0, 400.0, 300.0);
   double y1 = axis.java2DToValue(75.0, dataArea, RectangleEdge.LEFT);
   assertEquals(y1, 95.8333333, EPSILON);
   double y2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT);
   assertEquals(y2, 95.8333333, EPSILON);
   double x1 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP);
   assertEquals(x1, 58.125, EPSILON);
   double x2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM);
   assertEquals(x2, 58.125, EPSILON);
   axis.setInverted(true);
   double y3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.LEFT);
   assertEquals(y3, 54.1666667, EPSILON);
   double y4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT);
   assertEquals(y4, 54.1666667, EPSILON);
   double x3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP);
   assertEquals(x3, 91.875, EPSILON);
   double x4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM);
   assertEquals(x4, 91.875, EPSILON);
 }
Пример #11
0
 // configuramos el eje y de la gráfica (números enteros de dos en dos y rango entre 120 y 135)
 private void configurarRangeAxis(NumberAxis rangeAxis) {
   rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
   rangeAxis.setTickUnit(new NumberTickUnit(1));
   rangeAxis.setRange(-5, 5);
 }
Пример #12
0
 /**
  * Overridden version that calls original and then sets up flag for log axis processing.
  *
  * @param range the new range.
  */
 public void setRange(Range range) {
   super.setRange(range); // call parent method
   setupSmallLogFlag(); // setup flag based on bounds values
 }
  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;
  }
Пример #14
0
  private JFreeChart display(
      String title, int height, int width, String category, List<Report> toolResults) {

    JFrame f = new JFrame(title);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // averages
    ArrayList<Double> averageFalseRates = new ArrayList<Double>();

    ArrayList<Double> averageTrueRates = new ArrayList<Double>();
    double averageFalseRate = 0;
    double averageTrueRate = 0;

    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries series = new XYSeries("Scores");
    for (int i = 0; i < toolResults.size(); i++) {
      Report toolReport = toolResults.get(i);
      OverallResult overallResults = toolReport.getOverallResults().getResults(category);
      series.add(
          overallResults.getFalsePositiveRate() * 100, overallResults.getTruePositiveRate() * 100);
      if (toolReport.isCommercial()) {
        averageFalseRates.add(overallResults.getFalsePositiveRate());

        averageTrueRates.add(overallResults.getTruePositiveRate());
      }
    }

    for (double d : averageFalseRates) {
      averageFalseRate += d;
    }
    averageFalseRate = averageFalseRate / averageFalseRates.size();

    for (double d : averageTrueRates) {
      averageTrueRate += d;
    }
    averageTrueRate = averageTrueRate / averageTrueRates.size();

    series.add(averageFalseRate * 100, averageTrueRate * 100);
    dataset.addSeries(series);
    afr = averageFalseRate;
    atr = averageTrueRate;

    chart =
        ChartFactory.createScatterPlot(
            title,
            "False Positive Rate",
            "True Positive Rate",
            dataset,
            PlotOrientation.VERTICAL,
            true,
            true,
            false);
    String fontName = "Arial";
    DecimalFormat pctFormat = new DecimalFormat("0'%'");

    theme = (StandardChartTheme) org.jfree.chart.StandardChartTheme.createJFreeTheme();
    theme.setExtraLargeFont(new Font(fontName, Font.PLAIN, 24)); // title
    theme.setLargeFont(new Font(fontName, Font.PLAIN, 20)); // axis-title
    theme.setRegularFont(new Font(fontName, Font.PLAIN, 16));
    theme.setSmallFont(new Font(fontName, Font.PLAIN, 12));
    theme.setRangeGridlinePaint(Color.decode("#C0C0C0"));
    theme.setPlotBackgroundPaint(Color.white);
    theme.setChartBackgroundPaint(Color.white);
    theme.setGridBandPaint(Color.red);
    theme.setAxisOffset(new RectangleInsets(0, 0, 0, 0));
    theme.setBarPainter(new StandardBarPainter());
    theme.setAxisLabelPaint(Color.decode("#666666"));
    theme.apply(chart);

    XYPlot xyplot = chart.getXYPlot();
    NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();
    NumberAxis domainAxis = (NumberAxis) xyplot.getDomainAxis();

    xyplot.setOutlineVisible(true);

    rangeAxis.setRange(-5, 109.99);
    rangeAxis.setNumberFormatOverride(pctFormat);
    rangeAxis.setTickLabelPaint(Color.decode("#666666"));
    rangeAxis.setMinorTickCount(5);
    rangeAxis.setTickUnit(new NumberTickUnit(10));
    rangeAxis.setAxisLineVisible(true);
    rangeAxis.setMinorTickMarksVisible(true);
    rangeAxis.setTickMarksVisible(true);
    rangeAxis.setLowerMargin(10);
    rangeAxis.setUpperMargin(10);
    xyplot.setRangeGridlineStroke(new BasicStroke());
    xyplot.setRangeGridlinePaint(Color.lightGray);
    xyplot.setRangeMinorGridlinePaint(Color.decode("#DDDDDD"));
    xyplot.setRangeMinorGridlinesVisible(true);

    domainAxis.setRange(-5, 105);
    domainAxis.setNumberFormatOverride(pctFormat);
    domainAxis.setTickLabelPaint(Color.decode("#666666"));
    domainAxis.setMinorTickCount(5);
    domainAxis.setTickUnit(new NumberTickUnit(10));
    domainAxis.setAxisLineVisible(true);
    domainAxis.setTickMarksVisible(true);
    domainAxis.setMinorTickMarksVisible(true);
    domainAxis.setLowerMargin(10);
    domainAxis.setUpperMargin(10);
    xyplot.setDomainGridlineStroke(new BasicStroke());
    xyplot.setDomainGridlinePaint(Color.lightGray);
    xyplot.setDomainMinorGridlinePaint(Color.decode("#DDDDDD"));
    xyplot.setDomainMinorGridlinesVisible(true);

    chart.setTextAntiAlias(true);
    chart.setAntiAlias(true);
    chart.removeLegend();
    chart.setPadding(new RectangleInsets(20, 20, 20, 20));
    xyplot.getRenderer().setSeriesPaint(0, Color.decode("#4572a7"));

    //        // setup item labels
    //        XYItemRenderer renderer = xyplot.getRenderer();
    //        Shape circle = new Ellipse2D.Float(-2.0f, -2.0f, 7.0f, 7.0f);
    //        for ( int i = 0; i < dataset.getSeriesCount(); i++ ) {
    //            renderer.setSeriesShape(i, circle);
    //            renderer.setSeriesPaint(i, Color.blue);
    //            String label = ""+((String)dataset.getSeries(i).getKey());
    //            int idx = label.indexOf( ':');
    //            label = label.substring( 0, idx );
    //            StandardXYItemLabelGenerator generator = new StandardXYItemLabelGenerator(label);
    //            renderer.setSeriesItemLabelGenerator(i, generator);
    //            renderer.setSeriesItemLabelsVisible(i, true);
    //            ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
    // TextAnchor.BASELINE_CENTER );
    //            renderer.setSeriesPositiveItemLabelPosition(i, position);
    //        }

    makeDataLabels(category, toolResults, xyplot);
    makeLegend(category, toolResults, 57, 48, dataset, xyplot);

    Stroke dashed =
        new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] {6, 3}, 0);
    for (XYDataItem item : (List<XYDataItem>) series.getItems()) {
      double x = item.getX().doubleValue();
      double y = item.getY().doubleValue();
      double z = (x + y) / 2;
      XYLineAnnotation score = new XYLineAnnotation(x, y, z, z, dashed, Color.blue);
      xyplot.addAnnotation(score);
    }

    //        // put legend inside plot
    //        LegendTitle lt = new LegendTitle(xyplot);
    //        lt.setItemFont(theme.getSmallFont());
    //        lt.setPosition(RectangleEdge.RIGHT);
    //        lt.setItemFont(theme.getSmallFont());
    //        XYTitleAnnotation ta = new XYTitleAnnotation(.7, .55, lt, RectangleAnchor.TOP_LEFT);
    //        ta.setMaxWidth(0.48);
    //        xyplot.addAnnotation(ta);

    // draw guessing line
    XYLineAnnotation guessing = new XYLineAnnotation(-5, -5, 105, 105, dashed, Color.red);
    xyplot.addAnnotation(guessing);

    XYPointerAnnotation worse =
        makePointer(75, 5, "Worse than guessing", TextAnchor.TOP_CENTER, 90);
    xyplot.addAnnotation(worse);

    XYPointerAnnotation better =
        makePointer(25, 100, "Better than guessing", TextAnchor.BOTTOM_CENTER, 270);
    xyplot.addAnnotation(better);

    XYTextAnnotation stroketext =
        new XYTextAnnotation("                     Random Guess", 88, 107);
    stroketext.setTextAnchor(TextAnchor.CENTER_RIGHT);
    stroketext.setBackgroundPaint(Color.white);
    stroketext.setPaint(Color.red);
    stroketext.setFont(theme.getRegularFont());
    xyplot.addAnnotation(stroketext);

    XYLineAnnotation strokekey = new XYLineAnnotation(58, 107, 68, 107, dashed, Color.red);
    xyplot.setBackgroundPaint(Color.white);
    xyplot.addAnnotation(strokekey);

    ChartPanel cp =
        new ChartPanel(
            chart, height, width, 400, 400, 1200, 1200, false, false, false, false, false, false);
    f.add(cp);
    f.pack();
    f.setLocationRelativeTo(null);
    //      f.setVisible(true);

    return chart;
  }
Пример #15
0
  public Drawable createChart(ADCDataset dataset, Dimension dimension) {
    JFreeChart chart =
        ChartFactory.createBarChart(
            "", // chart title
            "", // domain axis label
            "", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // the plot orientation
            false, // legend
            false, // tooltips
            false // urls
            );
    TextTitle textTitle = new TextTitle(dataset.get(Attribute.TITLE), TITLE_FONT);
    textTitle.setPadding(new RectangleInsets(10, 0, 0, 0));
    chart.setTitle(textTitle);

    chart.addLegend(createLegend(dataset.getRowKey(0).toString(), dataset.getRowKey(1).toString()));
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setOutlineVisible(false);
    plot.setAxisOffset(new RectangleInsets(0, 0, 0, 0));
    plot.setDomainGridlinesVisible(false);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.gray);
    plot.setRangeGridlineStroke(new BasicStroke(2));

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setAutoTickUnitSelection(true);
    rangeAxis.setTickUnit(new NumberTickUnit(0.2, percentFormatter()));
    rangeAxis.setAxisLineVisible(true);
    rangeAxis.setLabel(dataset.get(Attribute.Y_AXIS_LABEL));
    rangeAxis.setAxisLineStroke(new BasicStroke(2));
    rangeAxis.setAxisLinePaint(Color.black);
    rangeAxis.setTickMarksVisible(false);
    rangeAxis.setLabelPaint(AXIS_LABEL_COLOR);
    rangeAxis.setLabelFont(AXIS_LABEL_FONT);
    rangeAxis.setLabelInsets(new RectangleInsets(0, 0, 0, 0));
    rangeAxis.setUpperMargin(0);
    rangeAxis.setAutoRange(false);
    rangeAxis.setRange(0, 1);

    CategoryAxis cAxis = plot.getDomainAxis();
    cAxis.setTickMarksVisible(false);
    cAxis.setAxisLinePaint(Color.black);
    cAxis.setAxisLineStroke(new BasicStroke(2));
    cAxis.setLabel(dataset.get(Attribute.X_AXIS_LABEL));
    cAxis.setTickLabelsVisible(true);
    cAxis.setUpperMargin(0.05);
    cAxis.setLowerMargin(0.05);
    cAxis.setTickLabelFont(CAXIS_LABEL_FONT);
    cAxis.setTickLabelPaint(Color.black);
    CustomBarRenderer renderer = new CustomBarRenderer();
    plot.setRenderer(renderer);
    renderer.setDrawBarOutline(false);
    renderer.setBaseItemLabelsVisible(false);
    renderer.setShadowVisible(false);
    renderer.setBarPainter(new StandardBarPainter());
    renderer.setMaximumBarWidth(0.08);
    renderer.setItemMargin(0.01);
    return new JFreeChartDrawable(chart, dimension);
  }
  public String generateXYChart(
      String section, HttpSession session, PrintWriter pw, String courseId, int studentId) {
    /*int groupId=0;
                if (groupName.equals("All")){
                    groupId=0;
                }else{
                     groupId = studStatisticBean.getGroupIdByName(groupName);
    }*/
    String filename = null;
    try {
      //  Retrieve list of WebHits
      StudentsConceptChartDataSet cDataSet =
          new StudentsConceptChartDataSet(studStatisticBean, courseId, studentId);
      ArrayList list = cDataSet.getDataByHitConcept(section);
      //  Throw a custom NoDataException if there is no data
      if (list.size() == 0) {
        System.out.println("No data has been found");
        throw new NoDataException();
      }
      //  Create and populate an XYSeries Collection
      XYSeries dataSeries = new XYSeries("Students progress line");
      Iterator iter = list.listIterator();
      while (iter.hasNext()) {
        StudentsConceptHit ch = (StudentsConceptHit) iter.next();
        dataSeries.add(ch.getOrdNumb(), ch.getHitDegree());
      }
      XYSeriesCollection xyDataset = new XYSeriesCollection(dataSeries);

      NumberFormat nf = NumberFormat.getIntegerInstance();
      NumberFormat nf2 = NumberFormat.getInstance();

      String cTitle = null;
      // StandardXYToolTipGenerator ttg = new
      // StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,nf,nf2);
      CustomXYToolTipGenerator ttg = new CustomXYToolTipGenerator();
      ttg.addToolTipSeries(cDataSet.getConceptNames());
      StandardXYURLGenerator sxyUrlGen =
          new StandardXYURLGenerator("#", xyDataset.getSeriesName(0), "PassedConceptOrdNum");

      ValueAxis ordNumAxis = new NumberAxis("Concept ordinal number");
      NumberAxis valueAxis = new NumberAxis("Current knowledge");
      // valueAxis.setAutoRangeIncludesZero(true);
      valueAxis.setRange(0.0, 6.0); // override default
      ordNumAxis.setAutoRange(true);
      ordNumAxis.setLowerMargin(0.0);

      StandardXYItemRenderer renderer =
          new StandardXYItemRenderer(
              StandardXYItemRenderer.LINES + StandardXYItemRenderer.SHAPES, ttg, sxyUrlGen);
      Marker marker = new ValueMarker(1.50); // /
      Marker marker2 = new ValueMarker(2.50);
      Marker marker3 = new ValueMarker(3.50);
      Marker marker4 = new ValueMarker(4.50);
      Marker marker5 = new ValueMarker(5.00);

      renderer.setShapesFilled(true);
      XYPlot plot = new XYPlot(xyDataset, ordNumAxis, valueAxis, renderer);

      plot.addRangeMarker(marker);
      plot.addRangeMarker(marker2);
      plot.addRangeMarker(marker3);
      plot.addRangeMarker(marker4);
      plot.addRangeMarker(marker5);

      XYTextAnnotation xyBad = new XYTextAnnotation("Bad", 1, 1);
      xyBad.setX(0.2);
      xyBad.setY(0.75);
      XYTextAnnotation xyNotBad = new XYTextAnnotation("Not Bad", 1, 1);
      xyNotBad.setX(0.2);
      xyNotBad.setY(2);
      XYTextAnnotation xyGood = new XYTextAnnotation("Good", 1, 1);
      xyGood.setX(0.2);
      xyGood.setY(3);
      XYTextAnnotation xyVeryGood = new XYTextAnnotation("Very Good", 1, 1);
      xyVeryGood.setX(0.2);
      xyVeryGood.setY(4);
      XYTextAnnotation xyExcellent = new XYTextAnnotation("Excellent", 1, 1);
      xyExcellent.setX(0.2);
      xyExcellent.setY(4.75);

      XYTextAnnotation xyExpert = new XYTextAnnotation("Expert", 1, 1);
      xyExpert.setX(0.2);
      xyExpert.setY(5.25);

      plot.addAnnotation(xyBad);
      plot.addAnnotation(xyNotBad);
      plot.addAnnotation(xyGood);
      plot.addAnnotation(xyVeryGood);
      plot.addAnnotation(xyExcellent);
      plot.addAnnotation(xyExpert);

      JFreeChart chart = new JFreeChart("", 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;
  }
Пример #17
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;
  }
Пример #18
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;
  }