/** Confirm that the equals method can distinguish all the required fields. */
  public void testEquals() {

    NumberAxis a1 = new NumberAxis("Test");
    NumberAxis a2 = new NumberAxis("Test");
    assertTrue(a1.equals(a2));

    // private boolean autoRangeIncludesZero;
    a1.setAutoRangeIncludesZero(false);
    assertFalse(a1.equals(a2));
    a2.setAutoRangeIncludesZero(false);
    assertTrue(a1.equals(a2));

    // private boolean autoRangeStickyZero;
    a1.setAutoRangeStickyZero(false);
    assertFalse(a1.equals(a2));
    a2.setAutoRangeStickyZero(false);
    assertTrue(a1.equals(a2));

    // private NumberTickUnit tickUnit;
    a1.setTickUnit(new NumberTickUnit(25.0));
    assertFalse(a1.equals(a2));
    a2.setTickUnit(new NumberTickUnit(25.0));
    assertTrue(a1.equals(a2));

    // private NumberFormat numberFormatOverride;
    a1.setNumberFormatOverride(new DecimalFormat("0.00"));
    assertFalse(a1.equals(a2));
    a2.setNumberFormatOverride(new DecimalFormat("0.00"));
    assertTrue(a1.equals(a2));
  }
Beispiel #2
0
  public JFreeChart createChart(int size) {
    CategoryDataset paramCategoryDataset = createDataset(size);
    // 创建主题样式
    StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
    // 设置标题字体
    standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));
    // 设置图例的字体
    standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 12));
    // 设置轴向的字体
    standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 12));
    // 应用主题样式
    ChartFactory.setChartTheme(standardChartTheme);
    JFreeChart localJFreeChart =
        ChartFactory.createLineChart(
            title, "期号", yTitle, paramCategoryDataset, PlotOrientation.VERTICAL, true, true, false);
    CategoryPlot localCategoryPlot = (CategoryPlot) localJFreeChart.getPlot();
    //		SymbolAxis localSymbolAxis = new SymbolAxis("个数", new String[] {
    //				"0", "1", "2", "3", "4", "5", "6" });
    //		localCategoryPlot.setRangeAxis(localSymbolAxis);
    ChartUtilities.applyCurrentTheme(localJFreeChart);
    LineAndShapeRenderer xyitem = (LineAndShapeRenderer) localCategoryPlot.getRenderer();
    CategoryPlot plot = (CategoryPlot) localJFreeChart.getPlot();
    // 设置网格背景颜色
    plot.setBackgroundPaint(Color.white);
    // 设置网格竖线颜色
    plot.setDomainGridlinePaint(Color.black);
    // 设置网格横线颜色
    plot.setRangeGridlinePaint(Color.black);
    // 设置曲线图与xy轴的距离
    plot.setAxisOffset(new RectangleInsets(0D, 0D, 0D, 0D));

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setAutoRangeIncludesZero(true);
    if ("和值".equals(type)) {
      rangeAxis.setLowerBound(70);
      rangeAxis.setTickUnit(new NumberTickUnit(10));
    } else {
      rangeAxis.setLowerBound(0);
      rangeAxis.setTickUnit(new NumberTickUnit(1));
    }
    //		rangeAxis.setUpperMargin(0.20);
    // 设置曲线显示各数据点的值
    xyitem.setBaseItemLabelsVisible(true);
    xyitem.setBasePositiveItemLabelPosition(
        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
    xyitem.setSeriesStroke(0, new BasicStroke(1.5F));
    xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 14));
    xyitem.setSeriesShapesVisible(0, true);
    plot.setRenderer(xyitem);
    return localJFreeChart;
  }
 /**
  * Set lower and upper limits for an ordinate
  *
  * @param i Axis index
  * @param lower Lower limit
  * @param upper Upper limit
  * @param tick Tick unit
  */
 public void setOrdinateRange(int i, double lower, double upper, double tick) {
   NumberAxis e = AxesList.get(i);
   e.setAutoRange(false);
   e.setLowerBound(lower);
   e.setUpperBound(upper);
   e.setTickUnit(new NumberTickUnit(tick));
 }
 protected void selectVerticalAutoTickUnit(
     Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
   double tickLabelHeight = estimateMaximumTickLabelHeight(g2);
   TickUnitSource tickUnits = getStandardTickUnits();
   TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());
   double unitHeight = lengthToJava2D(unit1.getSize(), dataArea, edge);
   double guess = unit1.getSize();
   if (unitHeight > 0.0d) {
     guess = (tickLabelHeight / unitHeight) * unit1.getSize();
   }
   NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(guess);
   if (estimateMaximumTickLabelHeight(g2) > lengthToJava2D(unit2.getSize(), dataArea, edge)) {
     unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);
   }
   setTickUnit(unit2, DEFAULT_VERTICAL_TICK_LABELS, DEFAULT_VERTICAL_TICK_LABELS);
 }
 protected void selectHorizontalAutoTickUnit(
     Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
   double tickLabelWidth = estimateMaximumTickLabelWidth(g2, getTickUnit());
   TickUnitSource tickUnits = getStandardTickUnits();
   TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());
   NumberTickUnit unit2 =
       (NumberTickUnit)
           tickUnits.getCeilingTickUnit(
               (tickLabelWidth / lengthToJava2D(unit1.getSize(), dataArea, edge))
                   * unit1.getSize());
   if (estimateMaximumTickLabelWidth(g2, unit2)
       > lengthToJava2D(unit2.getSize(), dataArea, edge)) {
     unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);
   }
   setTickUnit(unit2, DEFAULT_VERTICAL_TICK_LABELS, DEFAULT_VERTICAL_TICK_LABELS);
 }
  private static JFreeChart createDistributionViewChart() {
    XYPlot plot = new XYPlot();

    XYLineAndShapeRenderer dRenderer = new XYSplineRenderer();
    dRenderer.setBaseShapesVisible(false);
    dRenderer.setAutoPopulateSeriesPaint(false);
    dRenderer.setAutoPopulateSeriesStroke(false);
    dRenderer.setBaseStroke(TsCharts.getStrongStroke(LinesThickness.Thin));
    dRenderer.setDrawSeriesLineAsPath(true); // not sure if useful
    plot.setDataset(DISTRIBUTION_INDEX, Charts.emptyXYDataset());
    plot.setRenderer(DISTRIBUTION_INDEX, dRenderer);

    XYBarRenderer hRenderer = new XYBarRenderer();
    hRenderer.setShadowVisible(false);
    hRenderer.setDrawBarOutline(true);
    hRenderer.setAutoPopulateSeriesPaint(false);
    hRenderer.setAutoPopulateSeriesOutlinePaint(false);
    hRenderer.setBaseSeriesVisibleInLegend(false);
    plot.setDataset(HISTOGRAM_INDEX, Charts.emptyXYDataset());
    plot.setRenderer(HISTOGRAM_INDEX, hRenderer);

    NumberAxis domainAxis = new NumberAxis();
    domainAxis.setTickLabelPaint(TsCharts.CHART_TICK_LABEL_COLOR);
    plot.setDomainAxis(domainAxis);
    plot.setDomainGridlinesVisible(false);

    NumberAxis rangeAxis = new NumberAxis();
    rangeAxis.setTickLabelPaint(TsCharts.CHART_TICK_LABEL_COLOR);
    rangeAxis.setTickUnit(new NumberTickUnit(0.05));
    rangeAxis.setNumberFormatOverride(new DecimalFormat("0.###"));
    plot.setRangeAxis(rangeAxis);

    plot.mapDatasetToDomainAxis(0, 0);
    plot.mapDatasetToRangeAxis(0, 0);
    plot.mapDatasetToDomainAxis(1, 0);
    plot.mapDatasetToRangeAxis(1, 0);

    JFreeChart result = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    result.setPadding(TsCharts.CHART_PADDING);
    result.getTitle().setFont(TsCharts.CHART_TITLE_FONT);
    result.getLegend().setFrame(BlockBorder.NONE);
    result.getLegend().setBackgroundPaint(null);
    return result;
  }
  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;
  }
Beispiel #8
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);
 }
Beispiel #9
0
 // configuramos el eje X de la gráfica (se muestran números enteros y de uno en uno)
 private void configurarDomainAxis(NumberAxis domainAxis) {
   domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
   domainAxis.setTickUnit(new NumberTickUnit(10));
 }
  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;
  }
  /**
   * Generates a chart in PNG format.
   *
   * @param outputFile the output file, it should exist.
   * @param pxWidth the image width in pixels.
   * @param pxHeight the image height in pixels.
   * @param chartTitle the chart title, may be null.
   * @param xAxisTitle the x axis title
   * @param yDataSeriesRange the axis range (null for auto)
   * @param yDataSeriesTitles the Y axis titles.
   * @param timeValuesInSeconds the time values in seconds
   * @param yDataSeries the Y axis value series.
   * @param yDataSeriesColors the Y axis value series drawing colors.
   * @param yDataSeriesTickSuffix TODO explain argument yDataSeriesTickSuffix
   * @param drawBorder draw, or not, the border.
   * @param backgroundColor the chart background color.
   */
  final void generatePngChart(
      File outputFile,
      int pxWidth,
      int pxHeight,
      String chartTitle,
      String xAxisTitle,
      String[] yDataSeriesTitles,
      double[] timeValuesInSeconds,
      double[][] yDataSeriesRange,
      double[][] yDataSeries,
      Color[] yDataSeriesColors,
      String[] yDataSeriesTickSuffix,
      boolean drawBorder,
      Color backgroundColor) {

    // Domain axis
    NumberAxis xAxis = new NumberAxis(xAxisTitle);
    xAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    xAxis.setLabelPaint(Color.black);
    xAxis.setTickLabelPaint(Color.black);

    double maxSeconds = getMaxValue(timeValuesInSeconds);
    TimeAxisResolution xAxisRes = TimeAxisResolution.findTimeUnit(maxSeconds);
    xAxis.setTickUnit(new NumberTickUnit(xAxisRes.tickStep));
    double[] scaledTimeValues = xAxisRes.scale(timeValuesInSeconds);

    String tickSymbol =
        I18N.getString(locale, "running.job.details.chart.timeunit.symbol." + xAxisRes.name());
    xAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + tickSymbol + "'"));

    // First dataset
    String firstDataSetTitle = yDataSeriesTitles[0];
    XYDataset firstDataSet = createXYDataSet(firstDataSetTitle, scaledTimeValues, yDataSeries[0]);
    Color firstDataSetColor = yDataSeriesColors[0];

    // First range axis
    NumberAxis firstYAxis = new NumberAxis(firstDataSetTitle);

    firstYAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    setAxisRange(firstYAxis, yDataSeriesRange[0]);
    firstYAxis.setLabelPaint(firstDataSetColor);
    firstYAxis.setTickLabelPaint(firstDataSetColor);
    String firstAxisTickSuffix = yDataSeriesTickSuffix[0];
    if (firstAxisTickSuffix != null && !firstAxisTickSuffix.isEmpty()) {
      firstYAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + firstAxisTickSuffix + "'"));
    }

    // Create the plot with domain axis and first range axis
    XYPlot plot = new XYPlot(firstDataSet, xAxis, firstYAxis, null);

    XYLineAndShapeRenderer firstRenderer = new XYLineAndShapeRenderer(true, false);
    plot.setRenderer(firstRenderer);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    firstRenderer.setSeriesPaint(0, firstDataSetColor);

    // Now iterate on next axes
    for (int i = 1; i < yDataSeries.length; i++) {
      // Create axis
      String seriesTitle = yDataSeriesTitles[i];
      Color seriesColor = yDataSeriesColors[i];
      NumberAxis yAxis = new NumberAxis(seriesTitle);

      yAxis.setFixedDimension(CHART_AXIS_DIMENSION);
      setAxisRange(yAxis, yDataSeriesRange[i]);

      yAxis.setLabelPaint(seriesColor);
      yAxis.setTickLabelPaint(seriesColor);

      String yAxisTickSuffix = yDataSeriesTickSuffix[i];
      if (yAxisTickSuffix != null && !yAxisTickSuffix.isEmpty()) {
        yAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + yAxisTickSuffix + "'"));
      }

      // Create dataset and add axis to plot
      plot.setRangeAxis(i, yAxis);
      plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_LEFT);
      plot.setDataset(i, createXYDataSet(seriesTitle, scaledTimeValues, yDataSeries[i]));
      plot.mapDatasetToRangeAxis(i, i);
      XYItemRenderer renderer = new StandardXYItemRenderer();
      renderer.setSeriesPaint(0, seriesColor);
      plot.setRenderer(i, renderer);
    }

    // Create the chart
    JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, false);

    // Customize rendering
    chart.setBackgroundPaint(Color.white);
    chart.setBorderVisible(true);
    chart.setBorderPaint(Color.BLACK);

    // Render image
    try {
      ChartUtilities.saveChartAsPNG(outputFile, chart, pxWidth, pxHeight);
    } catch (IOException e) {
      LOG.error("Chart export failed", e);
    }
  }
Beispiel #12
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;
  }
 public void setTickUnit(NumberTickUnit unit) {
   setTickUnit(unit, DEFAULT_AUTO_RANGE_STICKY_ZERO, DEFAULT_AUTO_RANGE_STICKY_ZERO);
 }
  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);
  }
  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;
  }