예제 #1
0
    /**
     * Creates the demo chart.
     *
     * @return The chart.
     */
    private JFreeChart createChart() {

      XYDataset dataset1 = createDataset("Random 1", 100.0, new Minute(), 200);

      JFreeChart chart1 =
          ChartFactory.createTimeSeriesChart(
              "Crosshair Demo 1", "Time of Day", "Value", dataset1, true, true, false);

      chart1.setBackgroundPaint(Color.white);
      XYPlot plot = chart1.getXYPlot();
      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));

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

      XYItemRenderer renderer = plot.getRenderer();
      renderer.setPaint(Color.black);

      return chart1;
    }
  protected void configurePlot(Plot plot, JRChartPlot jrPlot) {

    super.configurePlot(plot, jrPlot);

    if (plot instanceof CategoryPlot) {
      CategoryPlot categoryPlot = (CategoryPlot) plot;
      CategoryItemRenderer categoryRenderer = categoryPlot.getRenderer();
      CategoryDataset categoryDataset = categoryPlot.getDataset();
      if (categoryDataset != null) {
        for (int i = 0; i < categoryDataset.getRowCount(); i++) {
          categoryRenderer.setSeriesOutlinePaint(i, ChartThemesConstants.TRANSPARENT_PAINT);
        }
      }
      categoryPlot.setRangeGridlinePaint(ChartThemesConstants.GRAY_PAINT_217);
      categoryPlot.setRangeGridlineStroke(new BasicStroke(0.5f));
      categoryPlot.setDomainGridlinesVisible(false);
      categoryPlot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    } else if (plot instanceof XYPlot) {
      XYPlot xyPlot = (XYPlot) plot;
      XYItemRenderer xyItemRenderer = xyPlot.getRenderer();
      XYDataset xyDataset = xyPlot.getDataset();
      if (xyDataset != null) {
        for (int i = 0; i < xyDataset.getSeriesCount(); i++) {
          xyItemRenderer.setSeriesOutlinePaint(i, ChartThemesConstants.TRANSPARENT_PAINT);
        }
      }
      xyPlot.setRangeGridlinePaint(ChartThemesConstants.GRAY_PAINT_217);
      xyPlot.setRangeGridlineStroke(new BasicStroke(0.5f));
      xyPlot.setDomainGridlinesVisible(false);
      xyPlot.setRangeZeroBaselineVisible(true);
    }
  }
  public void addLine(XYSeries series) {
    // add a second dataset and renderer...
    final XYItemRenderer renderer =
        new StandardXYItemRenderer() {
          // Stroke regularStroke = new BasicStroke(0.7f);
          public Color color;

          // @Override
          // public Stroke getItemStroke(int row, int column) {
          // return regularStroke;
          // }

          @Override
          public Paint getItemPaint(int row, int column) {
            return color;
          }

          // public Shape lookupLegendShape(int series) {
          //	return new Rectangle(15, 15);
          // }
        };

    renderer.setBasePaint(Color.LIGHT_GRAY);
    plot.setRenderer(line, renderer);
    final IntervalXYDataset cadenceData = new XYSeriesCollection(series);
    plot.setDataset(line, cadenceData);
    line++;
  }
예제 #4
0
  private static JFreeChart createChart(XYZDataset xyzdataset) {
    JFreeChart jfreechart =
        ChartFactory.createBubbleChart(
            "AGE vs WEIGHT vs WORK",
            "Weight (kg)",
            "AGE",
            xyzdataset,
            PlotOrientation.HORIZONTAL,
            true,
            true,
            false);

    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    xyplot.setForegroundAlpha(0.65F);
    XYItemRenderer xyitemrenderer = xyplot.getRenderer();
    xyitemrenderer.setSeriesPaint(0, Color.blue);
    NumberAxis numberaxis = (NumberAxis) xyplot.getDomainAxis();
    numberaxis.setLowerMargin(0.2);
    numberaxis.setUpperMargin(0.5);
    NumberAxis numberaxis1 = (NumberAxis) xyplot.getRangeAxis();
    numberaxis1.setLowerMargin(0.8);
    numberaxis1.setUpperMargin(0.9);

    return jfreechart;
  }
 /** Check that setting a tool tip generator for a series does override the default generator. */
 public void testSetSeriesToolTipGenerator() {
   XYPlot plot = (XYPlot) this.chart.getPlot();
   XYItemRenderer renderer = plot.getRenderer();
   StandardXYToolTipGenerator tt = new StandardXYToolTipGenerator();
   renderer.setSeriesToolTipGenerator(0, tt);
   XYToolTipGenerator tt2 = renderer.getToolTipGenerator(0, 0);
   assertTrue(tt2 == tt);
 }
예제 #6
0
 public static HashMap<String, ChartPanel> getGraphs(LinkedList<Game> games) {
   HashMap<String, XYSeriesCollection> datasets = new HashMap<>();
   for (int j = 0; j < games.size(); j++) {
     Game game = games.get(j);
     if (game == null) {
       continue;
     }
     for (String key : game.getVarData().keySet()) {
       if (datasets.containsKey(key)) {
         try {
           datasets.get(key).addSeries(createSeries(game.getVar(key), "" + game.getId()));
         } catch (Exception e) {
         }
       } else {
         datasets.put(key, new XYSeriesCollection());
         datasets.get(key).addSeries(createSeries(game.getVar(key), "" + game.getId()));
       }
     }
   }
   HashMap<String, ChartPanel> chartPanels = new HashMap<>();
   for (String key : datasets.keySet()) {
     JFreeChart chart =
         ChartFactory.createXYLineChart(
             key, // chart title
             "X", // x axis label
             "Y", // y axis label
             datasets.get(key), // data
             PlotOrientation.VERTICAL,
             false, // include legend
             true, // tooltips
             false // urls
             );
     XYPlot plot = chart.getXYPlot();
     XYItemRenderer rend = plot.getRenderer();
     for (int i = 0; i < games.size(); i++) {
       Game g = games.get(i);
       if (g.getWinner() == 1) {
         rend.setSeriesPaint(i, Color.RED);
       }
       if (g.getWinner() == 2) {
         rend.setSeriesPaint(i, Color.BLACK);
       }
       if (g.getWinner() == 0) {
         rend.setSeriesPaint(i, Color.PINK);
       }
     }
     ChartPanel chartPanel = new ChartPanel(chart);
     chartPanels.put(key, chartPanel);
   }
   return chartPanels;
 }
예제 #7
0
파일: GpsPlot.java 프로젝트: MMLoveMeMM/ARO
  @Override
  public void populate(XYPlot plot, AROTraceData analysis) {
    if (analysis != null) {
      gpsData.removeAllSeries();
      // create the GPS dataset...
      Map<GpsState, XYIntervalSeries> seriesMap =
          new EnumMap<GpsState, XYIntervalSeries>(GpsState.class);
      for (GpsState eventType : GpsState.values()) {
        XYIntervalSeries series = new XYIntervalSeries(eventType);
        seriesMap.put(eventType, series);
        gpsData.addSeries(series);
      }

      Iterator<GpsInfo> iter =
          analysis.getAnalyzerResult().getTraceresult().getGpsInfos().iterator();
      if (iter.hasNext()) {
        while (iter.hasNext()) {
          GpsInfo gpsEvent = iter.next();
          if (gpsEvent.getGpsState() != GpsState.GPS_DISABLED) {
            seriesMap
                .get(gpsEvent.getGpsState())
                .add(
                    gpsEvent.getBeginTimeStamp(),
                    gpsEvent.getBeginTimeStamp(),
                    gpsEvent.getEndTimeStamp(),
                    0.5,
                    0,
                    1);
          }
        }
      }

      XYItemRenderer renderer = plot.getRenderer();
      renderer.setSeriesPaint(gpsData.indexOf(GpsState.GPS_STANDBY), Color.YELLOW);
      renderer.setSeriesPaint(gpsData.indexOf(GpsState.GPS_ACTIVE), new Color(34, 177, 76));

      // Assign ToolTip to renderer
      renderer.setBaseToolTipGenerator(
          new XYToolTipGenerator() {
            @Override
            public String generateToolTip(XYDataset dataset, int series, int item) {
              GpsState eventType = (GpsState) gpsData.getSeries(series).getKey();
              return MessageFormat.format(
                  ResourceBundleHelper.getMessageString("gps.tooltip"),
                  dataset.getX(series, item),
                  ResourceBundleHelper.getEnumString(eventType));
            }
          });
    }
    plot.setDataset(gpsData);
  }
예제 #8
0
  public static void createGraphs(LinkedList<Game> games) {
    HashMap<String, XYSeriesCollection> datasets = new HashMap<>();
    for (Game game : games) {
      for (String key : game.getVarData().keySet()) {
        if (datasets.containsKey(key)) {
          try {
            datasets.get(key).addSeries(createSeries(game.getVar(key), "" + game.getId()));
          } catch (Exception e) {
          }
        } else {
          datasets.put(key, new XYSeriesCollection());
          datasets.get(key).addSeries(createSeries(game.getVar(key), "" + game.getId()));
        }
      }
    }

    for (String key : datasets.keySet()) {
      JFrame f = new JFrame();
      JFreeChart chart =
          ChartFactory.createXYLineChart(
              key, // chart title
              "X", // x axis label
              "Y", // y axis label
              datasets.get(key), // data
              PlotOrientation.VERTICAL,
              false, // include legend
              true, // tooltips
              false // urls
              );
      XYPlot plot = chart.getXYPlot();
      XYItemRenderer rend = plot.getRenderer();
      for (int i = 0; i < games.size(); i++) {
        Game g = games.get(i);
        if (g.getWinner() == 1) {
          rend.setSeriesPaint(i, Color.RED);
        }
        if (g.getWinner() == 2) {
          rend.setSeriesPaint(i, Color.BLACK);
        }
        if (g.getWinner() == 0) {
          rend.setSeriesPaint(i, Color.PINK);
        }
      }
      ChartPanel chartPanel = new ChartPanel(chart);
      f.setContentPane(chartPanel);
      f.pack();
      RefineryUtilities.centerFrameOnScreen(f);
      f.setVisible(true);
    }
  }
예제 #9
0
 private XYItemRenderer createScalabilityPlotRenderer(NumberFormat numberFormat) {
   XYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES_AND_LINES);
   // Use dashed line
   renderer.setSeriesStroke(
       0,
       new BasicStroke(
           1.0f,
           BasicStroke.CAP_ROUND,
           BasicStroke.JOIN_ROUND,
           1.0f,
           new float[] {2.0f, 6.0f},
           0.0f));
   return renderer;
 }
예제 #10
0
  public GenericScatterGraph(XYSeries series, String xAxis, String yAxis) {
    super();

    XYDataset xyDataset = new XYSeriesCollection(series);

    JFreeChart chart =
        ChartFactory.createScatterPlot(
            "", // chart title
            xAxis, // x axis label
            yAxis, // y axis label
            null,
            PlotOrientation.VERTICAL,
            false, // include legend
            true, // tooltips
            false // urls
            );

    chart.setBackgroundPaint(Color.darkGray);
    plot = chart.getXYPlot();
    plot.setDataset(0, xyDataset);
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);

    // Shape cross = ShapeUtilities.createDiamond(0.5f);
    Shape cross = ShapeUtilities.createDiagonalCross(0.5f, 0.5f);
    XYItemRenderer renderer = plot.getRenderer();
    renderer.setSeriesPaint(0, new Color(252, 141, 89));
    renderer.setSeriesShape(0, cross);

    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setTickLabelPaint(Color.white);
    domainAxis.setLabelPaint(Color.white);

    ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setTickLabelPaint(Color.white);
    rangeAxis.setLabelPaint(Color.white);

    chartPanel = new ChartPanel(chart);
    chartPanel.setSize(100, 800);

    setLayout(new BorderLayout());
    add(chartPanel, BorderLayout.CENTER);
    setBackground(Color.black);

    chartPanel.revalidate();
    setVisible(true);
  }
예제 #11
0
  @Override
  public void test() {
    super.test();

    numberOfPagesTest(1);

    JFreeChart chart = getChart("summary.chart1", 0);
    XYItemRenderer renderer = chart.getXYPlot().getRenderer();
    Assert.assertEquals("renderer", HighLowRenderer.class, renderer.getClass());
    Assert.assertEquals("show open ticks", true, ((HighLowRenderer) renderer).getDrawOpenTicks());
    Assert.assertEquals("show close ticks", true, ((HighLowRenderer) renderer).getDrawCloseTicks());
    highLowChartDataTest(
        chart,
        0,
        new Object[][] {
          {"serie", date1, 50d, 35d, 40d, 47d, 70d},
          {"serie", date2, 55d, 40d, 50d, 45d, 120d},
          {"serie", date3, 48d, 41d, 42d, 47d, 90d}
        });

    chart = getChart("summary.chart2", 0);
    Axis axis = chart.getXYPlot().getDomainAxis();
    Assert.assertEquals("category label", "time", axis.getLabel());
    Assert.assertEquals("category label color", Color.BLUE, axis.getLabelPaint());
    Assert.assertEquals(
        "category label font", new Font("Arial", Font.BOLD, 10), axis.getLabelFont());
    Assert.assertEquals("tick label color", Color.CYAN, axis.getTickLabelPaint());
    Assert.assertEquals(
        "tick label font", new Font("Arial", Font.ITALIC, 10), axis.getTickLabelFont());
    Assert.assertEquals("line color", Color.LIGHT_GRAY, axis.getAxisLinePaint());
    Assert.assertTrue("vertical tick labels", ((ValueAxis) axis).isVerticalTickLabels());

    chart = getChart("summary.chart3", 0);
    axis = chart.getXYPlot().getRangeAxis();
    Assert.assertEquals("value label", "value", axis.getLabel());
    Assert.assertEquals("value label color", Color.BLUE, axis.getLabelPaint());
    Assert.assertEquals("value label font", new Font("Arial", Font.BOLD, 10), axis.getLabelFont());
    Assert.assertEquals("tick label color", Color.CYAN, axis.getTickLabelPaint());
    Assert.assertEquals(
        "tick label font", new Font("Arial", Font.ITALIC, 10), axis.getTickLabelFont());
    Assert.assertEquals(
        "tick label mask", "10.00", ((NumberAxis) axis).getNumberFormatOverride().format(10));
    // Assert.assertEquals("line color", Color.LIGHT_GRAY, axis.getAxisLinePaint());
    Assert.assertEquals("range min value", 1d, ((ValueAxis) axis).getLowerBound());
    Assert.assertEquals("range max value", 15d, ((ValueAxis) axis).getUpperBound());
    Assert.assertTrue("vertical tick labels", ((ValueAxis) axis).isVerticalTickLabels());
  }
예제 #12
0
  /**
   * Create the charts
   *
   * @throws RemoteException On badness
   * @throws VisADException On badness
   */
  public void loadData() throws VisADException, RemoteException {
    createChart();
    List dataChoiceWrappers = getDataChoiceWrappers();
    try {
      for (int dataSetIdx = 0; dataSetIdx < plot.getDatasetCount(); dataSetIdx++) {
        MyHistogramDataset dataset = (MyHistogramDataset) plot.getDataset(dataSetIdx);
        dataset.removeAllSeries();
      }

      //            dataset.removeAllSeries();
      Hashtable props = new Hashtable();
      props.put(TrackDataSource.PROP_TRACKTYPE, TrackDataSource.ID_TIMETRACE);

      for (int paramIdx = 0; paramIdx < dataChoiceWrappers.size(); paramIdx++) {
        DataChoiceWrapper wrapper = (DataChoiceWrapper) dataChoiceWrappers.get(paramIdx);

        DataChoice dataChoice = wrapper.getDataChoice();
        FlatField data = getFlatField((FieldImpl) dataChoice.getData(null, props));
        Unit unit = ucar.visad.Util.getDefaultRangeUnits((FlatField) data)[0];
        double[][] samples = data.getValues(false);
        double[] actualValues = filterData(samples[0], getTimeValues(samples, data))[0];
        NumberAxis domainAxis = new NumberAxis(wrapper.getLabel(unit));

        XYItemRenderer renderer;
        if (stacked) {
          renderer = new StackedXYBarRenderer();
        } else {
          renderer = new XYBarRenderer();
        }
        plot.setRenderer(paramIdx, renderer);
        Color c = wrapper.getColor(paramIdx);
        domainAxis.setLabelPaint(c);
        renderer.setSeriesPaint(0, c);

        MyHistogramDataset dataset = new MyHistogramDataset();
        dataset.setType(HistogramType.FREQUENCY);
        dataset.addSeries(dataChoice.getName() + " [" + unit + "]", actualValues, bins);
        plot.setDomainAxis(paramIdx, domainAxis, false);
        plot.mapDatasetToDomainAxis(paramIdx, paramIdx);
        plot.setDataset(paramIdx, dataset);
      }

    } catch (Exception exc) {
      LogUtil.logException("Error creating data set", exc);
      return;
    }
  }
예제 #13
0
 /**
  * @param games the games to graph
  * @param key the variable to create the graph with
  * @param start if index, the index at which to start, else the percent in the game at which to
  *     start
  * @param stop if index, the index at which to end, else the percent in the game at which to end
  * @param index
  * @return
  */
 public static ChartPanel getCustomGraph(
     Game[] games, String key, double start, double stop, boolean index) {
   XYSeriesCollection dataset = new XYSeriesCollection();
   for (Game game : games) {
     ArrayList<Double> data = game.getVar(key);
     int begin;
     int end;
     if (index) {
       begin = (int) start;
       end = (int) stop;
     } else {
       begin = (int) (data.size() / start);
       end = (int) (data.size() / stop);
     }
     XYSeries series = GraphUtility.createSeries(data.subList(begin, end), "" + game.getId());
     dataset.addSeries(series);
   }
   JFreeChart chart =
       ChartFactory.createXYLineChart(
           key, // chart title
           "X", // x axis label
           "Y", // y axis label
           dataset, // data
           PlotOrientation.VERTICAL,
           false, // include legend
           true, // tooltips
           false // urls
           );
   XYPlot plot = chart.getXYPlot();
   XYItemRenderer rend = plot.getRenderer();
   for (int i = 0; i < games.length; i++) {
     Game g = games[i];
     if (g.getWinner() == 1) {
       rend.setSeriesPaint(i, Color.RED);
     }
     if (g.getWinner() == 2) {
       rend.setSeriesPaint(i, Color.BLACK);
     }
     if (g.getWinner() == 0) {
       rend.setSeriesPaint(i, Color.PINK);
     }
   }
   ChartPanel chartPanel = new ChartPanel(chart);
   return chartPanel;
 }
예제 #14
0
  public void finish(java.awt.Dimension preferredSize) {
    ChartUtilities.applyCurrentTheme(chart);

    XYPlot plot = (XYPlot) chart.getPlot();
    for (int i = 0; i < axisNum; i++) {
      XYItemRenderer renderer = plot.getRenderer(i);
      renderer.setSeriesPaint(0, colors[i]);

      ValueAxis axis = plot.getRangeAxis(i);
      axis.setLabelPaint(colors[i]);
      axis.setTickLabelPaint(colors[i]);
    }

    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(preferredSize);
    chartPanel.setDomainZoomable(true);
    chartPanel.setRangeZoomable(true);
  }
예제 #15
0
 private JFreeChart createChart() {
   XYDataset xydataset = createDataset("Random 1", 100D, new Minute(), 200);
   JFreeChart jfreechart =
       ChartFactory.createTimeSeriesChart(
           "Crosshair Demo 1", "Time of Day", "Value", xydataset, true, true, false);
   jfreechart.setBackgroundPaint(Color.white);
   XYPlot xyplot = (XYPlot) jfreechart.getPlot();
   xyplot.setOrientation(PlotOrientation.VERTICAL);
   xyplot.setBackgroundPaint(Color.lightGray);
   xyplot.setDomainGridlinePaint(Color.white);
   xyplot.setRangeGridlinePaint(Color.white);
   xyplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
   xyplot.setDomainCrosshairVisible(true);
   xyplot.setDomainCrosshairLockedOnData(false);
   xyplot.setRangeCrosshairVisible(false);
   XYItemRenderer xyitemrenderer = xyplot.getRenderer();
   xyitemrenderer.setSeriesPaint(0, Color.black);
   return jfreechart;
 }
예제 #16
0
  public static JFreeChart createXYLinePredictionChart(PredictionCenter center) {
    StatisticalPackageRunner runner = DBSeerGUI.runner;

    String title = runner.getVariableString("title");
    Object[] legends = (Object[]) runner.getVariableCell("legends");
    Object[] xCellArray = (Object[]) runner.getVariableCell("Xdata");
    Object[] yCellArray = (Object[]) runner.getVariableCell("Ydata");
    String xLabel = runner.getVariableString("Xlabel");
    String yLabel = runner.getVariableString("Ylabel");

    XYSeriesCollection dataSet = new XYSeriesCollection();

    int numLegends = legends.length;
    int numXCellArray = xCellArray.length;
    int numYCellArray = yCellArray.length;
    int dataCount = 0;

    if (numXCellArray != numYCellArray) {
      JOptionPane.showMessageDialog(
          null,
          "The number of X dataset and Y dataset does not match.",
          "The number of X dataset and Y dataset does not match.",
          JOptionPane.ERROR_MESSAGE);
      System.out.println(numXCellArray + " : " + numYCellArray);
      return null;
    }

    final java.util.List<String> transactionNames =
        center.getTrainConfig().getDataset(0).getTransactionTypeNames();
    for (int i = 0; i < numLegends; ++i) {
      String legend = (String) legends[i];
      for (int j = 0; j < transactionNames.size(); ++j) {
        if (legend.contains("Type " + (j + 1))) {
          legends[i] = legend.replace("Type " + (j + 1), transactionNames.get(j));
          break;
        }
      }
    }
    for (int j = 0; j < transactionNames.size(); ++j) {
      if (xLabel.contains("Type " + (j + 1))) {
        xLabel = xLabel.replace("Type " + (j + 1), transactionNames.get(j));
        break;
      }
    }
    for (int j = 0; j < transactionNames.size(); ++j) {
      if (yLabel.contains("Type " + (j + 1))) {
        yLabel = yLabel.replace("Type " + (j + 1), transactionNames.get(j));
        break;
      }
    }

    for (int i = 0; i < numYCellArray; ++i) {
      double[] xArray = (double[]) xCellArray[i];
      runner.eval("yArraySize = size(Ydata{" + (i + 1) + "});");
      runner.eval("yArray = Ydata{" + (i + 1) + "};");
      double[] yArraySize = runner.getVariableDouble("yArraySize");
      double[] yArray = runner.getVariableDouble("yArray");

      int xLength = xArray.length;
      int row = (int) yArraySize[0];
      int col = (int) yArraySize[1];

      for (int c = 0; c < col; ++c) {
        XYSeries series;
        int legendIdx = (dataCount >= numLegends) ? numLegends - 1 : dataCount;
        String legend = (String) legends[legendIdx];
        if (numLegends == 0) {
          series = new XYSeries("Data " + dataCount + 1);
        } else if (dataCount >= numLegends) {
          series = new XYSeries(legend + (dataCount + 1));
        } else {
          series = new XYSeries(legend);
        }

        for (int r = 0; r < row; ++r) {
          int xRow = (r >= xLength) ? xLength - 1 : r;
          double yValue = yArray[r + c * row];
          // remove negatives & NaN & infs.
          if (yValue < 0
              || yValue == Double.NaN
              || yValue == Double.POSITIVE_INFINITY
              || yValue == Double.NEGATIVE_INFINITY) {
            yValue = 0.0;
          }
          series.add(xArray[xRow], yValue);
        }
        dataSet.addSeries(series);
        ++dataCount;
      }
    }

    JFreeChart chart = ChartFactory.createXYLineChart(title, xLabel, yLabel, dataSet);

    // change 'predicted' data to have dotted lines.
    BasicStroke dashStroke = toStroke(STYLE_DASH);
    BasicStroke dotStroke = toStroke(STYLE_DOT);
    BasicStroke lineStroke = toStroke(STYLE_LINE);
    for (int i = 0; i < dataSet.getSeriesCount(); ++i) {
      String legend = (String) dataSet.getSeriesKey(i);
      XYPlot plot = chart.getXYPlot();
      XYItemRenderer renderer = plot.getRenderer();
      if (legend.contains("predicted") || legend.contains("Predicted")) {
        renderer.setSeriesStroke(i, dotStroke);
      } else {
        renderer.setSeriesStroke(i, lineStroke);
      }
    }

    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
  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;
  }
 @Override
 public void writeGraphFiles(BenchmarkReport benchmarkReport) {
   List<XYPlot> plotList = new ArrayList<XYPlot>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE);
   int seriesIndex = 0;
   for (SingleBenchmarkResult singleBenchmarkResult :
       problemBenchmarkResult.getSingleBenchmarkResultList()) {
     List<XYSeries> seriesList = new ArrayList<XYSeries>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE);
     // No direct ascending lines between 2 points, but a stepping line instead
     XYItemRenderer renderer = new XYStepRenderer();
     if (singleBenchmarkResult.isSuccess()) {
       BestScoreSingleStatistic singleStatistic =
           (BestScoreSingleStatistic)
               singleBenchmarkResult.getSingleStatistic(problemStatisticType);
       for (BestScoreStatisticPoint point : singleStatistic.getPointList()) {
         long timeMillisSpent = point.getTimeMillisSpent();
         double[] levelValues = ScoreUtils.extractLevelDoubles(point.getScore());
         for (int i = 0;
             i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE;
             i++) {
           if (i >= seriesList.size()) {
             seriesList.add(
                 new XYSeries(
                     singleBenchmarkResult
                         .getSolverBenchmarkResult()
                         .getNameWithFavoriteSuffix()));
           }
           seriesList.get(i).add(timeMillisSpent, levelValues[i]);
         }
       }
       // TODO if startingSolution is initialized and no improvement is made, a horizontal line
       // should be shown
       // Draw a horizontal line from the last new best step to how long the solver actually ran
       long timeMillisSpent = singleBenchmarkResult.getTimeMillisSpent();
       double[] bestScoreLevels = ScoreUtils.extractLevelDoubles(singleBenchmarkResult.getScore());
       for (int i = 0;
           i < bestScoreLevels.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE;
           i++) {
         if (i >= seriesList.size()) {
           seriesList.add(
               new XYSeries(
                   singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix()));
         }
         seriesList.get(i).add(timeMillisSpent, bestScoreLevels[i]);
       }
       if (singleStatistic.getPointList().size() <= 1) {
         // Workaround for
         // https://sourceforge.net/tracker/?func=detail&aid=3387330&group_id=15494&atid=115494
         renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES_AND_LINES);
       }
     }
     if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) {
       // Make the favorite more obvious
       renderer.setSeriesStroke(0, new BasicStroke(2.0f));
     }
     for (int i = 0; i < seriesList.size(); i++) {
       if (i >= plotList.size()) {
         plotList.add(createPlot(benchmarkReport, i));
       }
       plotList.get(i).setDataset(seriesIndex, new XYSeriesCollection(seriesList.get(i)));
       plotList.get(i).setRenderer(seriesIndex, renderer);
     }
     seriesIndex++;
   }
   graphFileList = new ArrayList<File>(plotList.size());
   for (int scoreLevelIndex = 0; scoreLevelIndex < plotList.size(); scoreLevelIndex++) {
     JFreeChart chart =
         new JFreeChart(
             problemBenchmarkResult.getName()
                 + " best score level "
                 + scoreLevelIndex
                 + " statistic",
             JFreeChart.DEFAULT_TITLE_FONT,
             plotList.get(scoreLevelIndex),
             true);
     graphFileList.add(
         writeChartToImageFile(
             chart,
             problemBenchmarkResult.getName() + "BestScoreStatisticLevel" + scoreLevelIndex));
   }
 }
 private BufferedImage generarGraficoLineal(
     String titulo,
     String ejeHorizontal,
     String ejeVertical,
     double[] valores,
     String[] funciones,
     boolean porcentaje,
     boolean leyenda,
     int anchoImagen,
     int altoImagen) {
   XYSeries frecObservadas = new XYSeries("Cantidades de resoluciones por calificación");
   // Calculamos las frecuencias por intervalo
   for (int i = 0; i < valores.length; i++) {
     frecObservadas.add(i, valores[i]);
   }
   XYDataset dataset = new XYSeriesCollection(frecObservadas);
   // Creamos el gráfico
   JFreeChart chart =
       ChartFactory.createXYLineChart(
           titulo,
           ejeHorizontal,
           ejeVertical,
           null,
           PlotOrientation.VERTICAL,
           leyenda,
           false,
           true);
   // Seteamos color de título
   chart.setBackgroundPaint(null);
   chart.setBorderVisible(false);
   chart.getTitle().setPaint(LookAndFeelEntropy.COLOR_FUENTE_TITULO_PANEL);
   chart.getTitle().setFont(LookAndFeelEntropy.FUENTE_TITULO_GRANDE);
   if (leyenda) {
     chart.getLegend().setItemFont(LookAndFeelEntropy.FUENTE_REGULAR);
     chart.getLegend().setBackgroundPaint(LookAndFeelEntropy.COLOR_TABLA_PRIMARIO);
   }
   // Seteamos datasets
   XYPlot xyplot = chart.getXYPlot();
   xyplot.setDataset(1, dataset);
   xyplot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
   // Seteamos características de la función lineal
   XYItemRenderer xyLineRendererObs = new XYLineAndShapeRenderer();
   xyLineRendererObs.setSeriesShape(0, new Line2D.Double(0.0, 0.0, 0.0, 0.0));
   xyLineRendererObs.setSeriesStroke(0, new BasicStroke(2.5f));
   xyLineRendererObs.setBasePaint(generarColorAleatorio(Color.orange));
   xyplot.setRenderer(1, xyLineRendererObs);
   // Seteamos color de labels de ejes
   ValueAxis axisX = new SymbolAxis(ejeHorizontal, funciones);
   axisX.setVerticalTickLabels(true);
   xyplot.setDomainAxis(axisX);
   xyplot.getDomainAxis().setTickLabelPaint(Color.BLACK);
   xyplot.getDomainAxis().setLabelPaint(Color.BLACK);
   xyplot.getDomainAxis().setTickLabelFont(LookAndFeelEntropy.FUENTE_REGULAR);
   xyplot.getRangeAxis().setTickLabelPaint(Color.BLACK);
   xyplot.getRangeAxis().setLabelPaint(Color.BLACK);
   xyplot.getRangeAxis().setTickLabelFont(LookAndFeelEntropy.FUENTE_REGULAR);
   // Seteamos porcentaje
   final NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();
   if (porcentaje) {
     rangeAxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
   } else {
     rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
   }
   // Seteamos transparencia de fondo
   Plot plot = chart.getPlot();
   plot.setBackgroundPaint(null);
   plot.setBackgroundImageAlpha(0.0f);
   plot.setOutlineVisible(false);
   // Generamos una imagen
   this.lastChart = chart;
   return chart.createBufferedImage(anchoImagen, altoImagen);
 }
예제 #21
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;
  }
  public void testHistogram1DAdapter() {

    IHistogram1D histogram = histogramFactory.createHistogram1D("h1d", 100, 0, 100);
    Random random = new Random();
    for (int i = 0; i < 100000; i++) {
      histogram.fill(random.nextInt(100));
    }

    Histogram1DAdapter adapter = new Histogram1DAdapter(histogram);

    // int getSeriesCount()
    int seriesCount = adapter.getSeriesCount();
    System.out.println("seriesCount: " + seriesCount);

    // int getItemCount(int series)
    int itemCount = adapter.getItemCount(VALUES);
    System.out.println("itemCount: " + itemCount);

    // Comparable getSeriesKey(int series)
    Comparable<?> seriesKey = adapter.getSeriesKey(VALUES);
    System.out.println("data series key: " + seriesKey);

    seriesKey = adapter.getSeriesKey(ERRORS);
    System.out.println("error series key: " + seriesKey);

    System.out.println();

    for (int item = 0; item < itemCount; item++) {

      System.out.println("item " + item);

      double x = adapter.getXValue(VALUES, item);
      double xLow = adapter.getStartXValue(VALUES, item);
      double xHigh = adapter.getEndXValue(VALUES, item);

      double y = adapter.getYValue(VALUES, item);
      double yLow = adapter.getStartYValue(VALUES, item);
      double yHigh = adapter.getEndYValue(VALUES, item);

      System.out.format(
          "  bin data (x,xLow,xHigh,y,yLow,yHigh) = %f,%f,%f,%f,%f,%f%n",
          x, xLow, xHigh, y, yLow, yHigh);

      x = adapter.getXValue(ERRORS, item);
      xLow = adapter.getStartXValue(ERRORS, item);
      xHigh = adapter.getEndXValue(ERRORS, item);

      y = adapter.getYValue(ERRORS, item);
      yLow = adapter.getStartYValue(ERRORS, item);
      yHigh = adapter.getEndYValue(ERRORS, item);

      System.out.format(
          "  error data (x,xLow,xHigh,y,yLow,yHigh) = %f,%f,%f,%f,%f,%f%n",
          x, xLow, xHigh, y, yLow, yHigh);

      x = adapter.getXValue(POINTS, item);
      y = adapter.getYValue(POINTS, item);
      System.out.format("  point data (x,y) = %f,%f%n", x, y);
    }
    System.out.println();
    System.out.println();

    System.out.println("printing step data ...");
    itemCount = adapter.getItemCount(STEPS);
    System.out.println("step itemCount: " + itemCount);
    for (int item = 0; item < itemCount; item++) {
      System.out.println("item " + item);
      double x = adapter.getXValue(STEPS, item);
      double y = adapter.getYValue(STEPS, item);
      // double y = adapter.getYValue(STEPS, item);
      System.out.format("  step data (x,y) = %f,%f%n", x, y);
    }

    // Set the axis labels.
    String[] labels = ConverterUtil.getAxisLabels(histogram);
    NumberAxis xAxis = new NumberAxis(labels[0]);
    NumberAxis yAxis = new NumberAxis(labels[1]);

    // Create the plot without any data.
    XYPlot plot = new XYPlot(null, xAxis, yAxis, null);

    // Bar chart
    XYDataset barData = new Histogram1DAdapter(histogram);
    XYBarRenderer barRenderer = new XYBarRenderer();
    barRenderer.setSeriesVisible(ERRORS, false);
    barRenderer.setSeriesVisible(POINTS, false);
    barRenderer.setSeriesVisible(STEPS, false);
    // barRenderer.setSeriesVisible(VALUES, false); // DEBUG
    barRenderer.setDrawBarOutline(true);
    plot.setDataset(VALUES, barData);
    plot.setRenderer(VALUES, barRenderer);

    // Errors
    XYDataset errors = new Histogram1DAdapter(histogram);
    XYErrorRenderer errorRenderer = new XYErrorRenderer();
    errorRenderer.setSeriesVisible(VALUES, false);
    errorRenderer.setSeriesVisible(POINTS, false);
    errorRenderer.setSeriesVisible(STEPS, false);
    // errorRenderer.setSeriesVisible(ERRORS, false); // DEBUG
    errorRenderer.setBaseShapesVisible(false);
    errorRenderer.setSeriesPaint(0, Color.black);
    plot.setDataset(ERRORS, errors);
    plot.setRenderer(ERRORS, errorRenderer);

    // Points
    XYDataset points = new Histogram1DAdapter(histogram);
    XYItemRenderer pointRenderer = new XYLineAndShapeRenderer();
    pointRenderer.setSeriesVisible(VALUES, false);
    pointRenderer.setSeriesVisible(ERRORS, false);
    pointRenderer.setSeriesVisible(STEPS, false);
    // pointRenderer.setSeriesVisible(POINTS, false); // DEBUG
    plot.setDataset(POINTS, points);
    plot.setRenderer(POINTS, pointRenderer);

    // Steps
    XYDataset steps = new Histogram1DAdapter(histogram);
    XYItemRenderer stepRenderer = new XYStepRenderer();
    stepRenderer.setSeriesVisible(VALUES, false);
    stepRenderer.setSeriesVisible(ERRORS, false);
    stepRenderer.setSeriesVisible(POINTS, false);
    // stepRenderer.setSeriesVisible(STEPS, false);
    plot.setDataset(STEPS, steps);
    plot.setRenderer(STEPS, stepRenderer);

    // Set proper rendering order.
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    // Set style.
    ChartFactory.setChartTheme(new DefaultChartTheme());
    XYBarRenderer.setDefaultShadowsVisible(false);

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

    // Show the chart in an application frame.
    ChartPanel panel = new ChartPanel(chart);
    ApplicationFrame frame = new ApplicationFrame("Histogram1DAdapterTest");
    frame.setContentPane(panel);
    frame.pack();
    RefineryUtilities.centerFrameOnScreen(frame);
    frame.setVisible(true);
  }
  /**
   * 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);
    }
  }
예제 #24
0
파일: XYChart.java 프로젝트: Delejnr/jeql
  /**
   * Creates a chart.
   *
   * @param dataset the dataset.
   * @return A chart.
   */
  private JFreeChart createChart(XYDataset dataset) {
    String chartType = getChartType();

    JFreeChart chart = null;
    if (chartType == CHART_TYPE_XY && param.isFilled)
      chart =
          ChartFactory.createXYAreaChart(
              param.title, // chart title
              param.axisXTitle,
              param.axisYTitle,
              dataset, // data
              param.plotOrientation,
              param.showLegend, // include legend
              false, // no tooltips
              false // no URLs
              );
    else if (chartType == CHART_TYPE_XY)
      chart =
          ChartFactory.createXYLineChart(
              param.title, // chart title
              param.axisXTitle,
              param.axisYTitle,
              dataset, // data
              param.plotOrientation,
              param.showLegend, // include legend
              false, // no tooltips
              false // no URLs
              );
    else if (chartType == CHART_TYPE_XY_STEP && param.isFilled)
      chart =
          ChartFactory.createXYStepAreaChart(
              param.title, // chart title
              param.axisXTitle,
              param.axisYTitle,
              dataset, // data
              param.plotOrientation,
              param.showLegend, // include legend
              false, // no tooltips
              false // no URLs
              );
    else if (chartType == CHART_TYPE_XY_STEP)
      chart =
          ChartFactory.createXYStepChart(
              param.title, // chart title
              param.axisXTitle,
              param.axisYTitle,
              dataset, // data
              param.plotOrientation,
              param.showLegend, // include legend
              false, // no tooltips
              false // no URLs
              );
    else if (chartType == CHART_TYPE_POLAR)
      chart =
          ChartFactory.createPolarChart(
              param.title, // chart title
              dataset, // data
              param.showLegend, // include legend
              false, // no tooltips
              false // no URLs
              );

    // show item labels for XY charts
    if (chartType != CHART_TYPE_POLAR) {
      XYItemRenderer rend = (XYItemRenderer) chart.getXYPlot().getRenderer();
      rend.setBaseItemLabelGenerator(new XYLabelItemGenerator(xyItems));
      // rend.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
      rend.setBaseItemLabelsVisible(true);
      // rr.setPlotShapes(true);
    }

    return chart;
  }
예제 #25
0
  public void createGraph(final String filename, final TransitRoute route) {

    HashMap<Id, Integer> stopIndex = new HashMap<Id, Integer>();
    int idx = 0;
    for (TransitRouteStop stop : route.getStops()) {
      stopIndex.put(stop.getStopFacility().getId(), idx);
      idx++;
    }

    HashSet<Id> vehicles = new HashSet<Id>();
    for (Departure dep : route.getDepartures().values()) {
      vehicles.add(dep.getVehicleId());
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    int numSeries = 0;
    double earliestTime = Double.POSITIVE_INFINITY;
    double latestTime = Double.NEGATIVE_INFINITY;

    for (Map.Entry<Id, List<Tuple<Id, Double>>> entry : this.positions.entrySet()) {
      if (vehicles.contains(entry.getKey())) {
        XYSeries series = new XYSeries("t", false, true);
        for (Tuple<Id, Double> pos : entry.getValue()) {
          Integer stopIdx = stopIndex.get(pos.getFirst());
          if (stopIdx != null) {
            double time = pos.getSecond().doubleValue();
            series.add(stopIdx.intValue(), time);
            if (time < earliestTime) {
              earliestTime = time;
            }
            if (time > latestTime) {
              latestTime = time;
            }
          }
        }
        dataset.addSeries(series);
        numSeries++;
      }
    }

    JFreeChart c =
        ChartFactory.createXYLineChart(
            "Route-Time Diagram, Route = " + route.getId(),
            "stops",
            "time",
            dataset,
            PlotOrientation.VERTICAL,
            false, // legend?
            false, // tooltips?
            false // URLs?
            );
    c.setBackgroundPaint(new Color(1.0f, 1.0f, 1.0f, 1.0f));

    XYPlot p = (XYPlot) c.getPlot();

    p.getRangeAxis().setInverted(true);
    p.getRangeAxis().setRange(earliestTime, latestTime);
    XYItemRenderer renderer = p.getRenderer();
    for (int i = 0; i < numSeries; i++) {
      renderer.setSeriesPaint(i, Color.black);
    }

    try {
      ChartUtilities.saveChartAsPNG(new File(filename), c, 1024, 768, null, true, 9);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #26
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;
  }
  /**
   * @param axis Axis name to wich the new series belongs
   * @param cs Series Coinfiguration
   */
  @Override
  public final void addSeries(String axis, SimpleSeriesConfiguration cs) {
    for (int i = 0; i < axes.size(); i++) {
      if (axes.get(i).getName().equals(axis)) {
        String strColor;
        javafx.scene.paint.Color color;
        int indice = seriesList.size();
        if (cs.getColor() == null) {
          color = getColor(indice);
        } else {
          color = cs.getColor();
        }
        strColor = color.toString();

        XYSeriesCollection dataset = datasetList.get(i);
        Series series =
            new Series(
                cs.getName(),
                "color: "
                    + strColor
                    + ";width: "
                    + String.valueOf(cs.getLineWidth())
                    + ";shape: "
                    + cs.getShapeName()
                    + ";",
                i,
                dataset.getSeriesCount());
        dataset.addSeries(series);

        XYItemRenderer renderer = plot.getRenderer(i);
        renderer.setSeriesPaint(dataset.getSeriesCount() - 1, scene2awtColor(color));

        SeriesShape simb =
            new SeriesShape(
                cs.getShapeName(), javafx.scene.paint.Color.web(strColor.replace("#", "0x")));

        if (cs.getLineWidth() > 0) {
          ((XYLineAndShapeRenderer) renderer)
              .setSeriesLinesVisible(dataset.getSeriesCount() - 1, true);
          renderer.setSeriesStroke(
              dataset.getSeriesCount() - 1, new BasicStroke(cs.getLineWidth()));
        } else {
          ((XYLineAndShapeRenderer) renderer)
              .setSeriesLinesVisible(dataset.getSeriesCount() - 1, false);
        }

        if (cs.getShapeName().equals("null")) {
          renderer.setSeriesShape(dataset.getSeriesCount() - 1, null);
          ((XYLineAndShapeRenderer) renderer)
              .setSeriesShapesVisible(dataset.getSeriesCount() - 1, false);
        } else {
          renderer.setSeriesShape(dataset.getSeriesCount() - 1, simb.getShapeAWT());
          ((XYLineAndShapeRenderer) renderer)
              .setSeriesShapesVisible(dataset.getSeriesCount() - 1, true);
          if (cs.getShapeName().contains("empty")) {
            ((XYLineAndShapeRenderer) renderer)
                .setSeriesShapesFilled(dataset.getSeriesCount() - 1, false);
          } else {
            ((XYLineAndShapeRenderer) renderer)
                .setSeriesShapesFilled(dataset.getSeriesCount() - 1, true);
          }
        }

        if (i == 0) {
          plot.setRenderer(renderer);
        } else {
          plot.setRenderer(i, renderer);
        }

        seriesList.add(series);

        final LegendAxis le = getLegendAxis(axis);
        final Label label = new Label(cs.toString());
        Platform.runLater(
            () -> {
              label.setStyle(
                  "fondo: "
                      + strChartBackgroundColor
                      + ";-fx-background-color: fondo;-fx-text-fill: ladder(fondo, white 49%, black 50%);-fx-padding:5px;-fx-background-radius: 5;-fx-font-size: "
                      + String.valueOf(fontSize)
                      + "px");
            });

        label.setOnMouseClicked(
            (MouseEvent t) -> {
              if (t.getClickCount() == 2) {
                for (int i1 = 0; i1 < seriesList.size(); i1++) {
                  if (seriesList.get(i1).getKey().toString().equals(label.getText())) {
                    editSeries(seriesList.get(i1));
                    break;
                  }
                }
              }
            });
        label.setOnMouseExited(
            (MouseEvent t) -> {
              label.setStyle(
                  label
                      .getStyle()
                      .replace("-fx-background-color: blue", "-fx-background-color: fondo"));
            });
        label.setOnMouseEntered(
            (MouseEvent t) -> {
              label.setStyle(
                  label
                      .getStyle()
                      .replace("-fx-background-color: fondo", "-fx-background-color: blue"));
              for (Node le1 : legendFrame.getChildren()) {
                if (le1 instanceof LegendAxis) {
                  le1.setStyle("-fx-background-color:" + strBackgroundColor);
                  ((LegendAxis) le1).selected = false;
                }
              }
            });
        label.setStyle(
            "fondo: "
                + strChartBackgroundColor
                + ";-fx-text-fill: white;-fx-background-color: fondo;-fx-padding:5px;-fx-background-radius: 5;-fx-font-size: "
                + String.valueOf(fontSize)
                + "px");

        le.getChildren().add(label);
        label.setGraphic(simb.getShapeGraphic());

        break;
      }
    }
  }