/** Replaces the chart's dataset and then checks that the new dataset is OK. */
  public void testReplaceDataset() {

    // create a dataset...
    Number[][] data =
        new Integer[][] {
          {new Integer(-30), new Integer(-20)},
          {new Integer(-10), new Integer(10)},
          {new Integer(20), new Integer(30)}
        };

    CategoryDataset newData = DatasetUtilities.createCategoryDataset("S", "C", data);

    LocalListener l = new LocalListener();
    this.chart.addChangeListener(l);
    CategoryPlot plot = (CategoryPlot) this.chart.getPlot();
    plot.setDataset(newData);
    assertEquals(true, l.flag);
    ValueAxis axis = plot.getRangeAxis();
    Range range = axis.getRange();
    assertTrue(
        "Expecting the lower bound of the range to be around -30: " + range.getLowerBound(),
        range.getLowerBound() <= -30);
    assertTrue(
        "Expecting the upper bound of the range to be around 30: " + range.getUpperBound(),
        range.getUpperBound() >= 30);
  }
 /**
  * Return the range of z-values in the specified dataset.
  *
  * @param dataset the dataset (<code>null</code> permitted).
  * @return The range (<code>null</code> if the dataset is <code>null</code> or empty).
  */
 public Range findZBounds(XYZDataset dataset) {
   if (dataset != null) {
     return DatasetUtilities.findZBounds(dataset);
   } else {
     return null;
   }
 }
Example #3
0
 /**
  * Returns the range of the values in this dataset's domain.
  *
  * @param includeInterval a flag that determines whether or not the x-interval is taken into
  *     account.
  * @return The range.
  */
 public Range getDomainBounds(boolean includeInterval) {
   if (includeInterval) {
     return this.intervalDelegate.getDomainBounds(includeInterval);
   } else {
     return DatasetUtilities.iterateDomainBounds(this, includeInterval);
   }
 }
 /**
  * Returns the range of values the renderer requires to display all the items from the specified
  * dataset.
  *
  * @param dataset the dataset (<code>null</code> permitted).
  * @return The range (<code>null</code> if the dataset is <code>null</code> or empty).
  */
 @Override
 public Range findRangeBounds(XYDataset dataset) {
   if (dataset != null) {
     return DatasetUtilities.findRangeBounds(dataset, true);
   } else {
     return null;
   }
 }
 /* (non-Javadoc)
  * @see com.feilong.tools.jfreechart.xy.FeiLongBaseXYChartEntity#setChildDefaultNumberAxisAttributes()
  */
 protected void setChildDefaultNumberAxisAttributes() {
   CategoryDataset categoryDataset = categoryPlot.getDataset();
   // 数据轴的数据标签 可以只显示整数标签,需要将AutoTickUnitSelection设false
   // numberAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
   double fudong = 0.5;
   NumberAxis numberAxis = getNumberAxis();
   // 设置最大值
   numberAxis.setUpperBound(
       DatasetUtilities.findMaximumRangeValue(categoryDataset).doubleValue() + fudong);
   // 设置最小值
   numberAxis.setLowerBound(
       DatasetUtilities.findMinimumRangeValue(categoryDataset).doubleValue() - fudong);
   // 设置坐标轴的最小值,默认的是0.00000001
   // numberAxis.setAutoRangeMinimumSize(1);
   // 是否强制在自动选择的数据范围中包含0
   numberAxis.setAutoRangeIncludesZero(false);
   // 纵轴显示范围
   // numberAxis.setRange(85, 100.5);
 }
 /**
  * Create a bar chart with sample data in the range -3 to +3.
  *
  * @return The chart.
  */
 private static JFreeChart createBarChart() {
   Number[][] data =
       new Integer[][] {
         {new Integer(-3), new Integer(-2)},
         {new Integer(-1), new Integer(1)},
         {new Integer(2), new Integer(3)}
       };
   CategoryDataset dataset = DatasetUtilities.createCategoryDataset("S", "C", data);
   return ChartFactory.createBarChart("Bar Chart", "Domain", "Range", dataset);
 }
  /**
   * Displays a signal (using the JFreeChart package).
   *
   * @param useChart if set to true, the signal is displaied as a bar chart (this is used for
   *     histograms).
   */
  public void display(boolean useChart) {

    JFreeChart chart;
    int nbSamples = getNbSamples();

    if (useChart) {
      String[] categories = new String[nbSamples];
      for (int i = 0; i < nbSamples; i++) {
        categories[i] = data.getX(i).toString();
      }
      String[] categoryNames = {"Histogram"};
      double[][] categoryData = new double[1][nbSamples];
      for (int i = 0; i < nbSamples; i++) {
        categoryData[0][i] = data.getY(i).doubleValue();
      }

      CategoryDataset categoryDataset =
          DatasetUtilities.createCategoryDataset(categoryNames, categories, categoryData);

      chart =
          ChartFactory.createBarChart(
              "Histogram", // Title
              "Data Value", // X axis label
              "Number of Elements", // Y axis label
              categoryDataset, // dataset
              PlotOrientation.VERTICAL, // orientation
              true, // legends
              true, // tool tips
              true);
    } else {
      XYDataset xyDataSet = new XYSeriesCollection(this.data);
      chart =
          ChartFactory.createXYLineChart(
              "Example Dataset", // Title
              "Abscissa", // X axis label
              "Ordinate", // Y axis label
              xyDataSet, // dataset
              PlotOrientation.VERTICAL, // orientation
              true, // legends
              true, // tool tips
              true); // urls

      XYPlot plot = (XYPlot) chart.getPlot();
      XYItemRenderer r = plot.getRenderer();
      if (r instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setSeriesShapesVisible(0, true);
        renderer.setSeriesShapesFilled(0, true);
      }
    }

    ChartFrame frame = new ChartFrame("Frame Title", chart);
    frame.setVisible(true);
    frame.setSize(512, 512);
  }
 /**
  * Returns the range of values the renderer requires to display all the items from the specified
  * dataset.
  *
  * @param dataset the dataset (<code>null</code> permitted).
  * @return The range (<code>null</code> if the dataset is <code>null</code> or empty).
  */
 public Range findRangeBounds(XYDataset dataset) {
   if (dataset != null) {
     if (this.renderAsPercentages) {
       return new Range(0.0, 1.0);
     } else {
       return DatasetUtilities.findStackedRangeBounds((TableXYDataset) dataset);
     }
   } else {
     return null;
   }
 }
 /**
  * Returns the lower and upper bounds (range) of the x-values in the specified dataset.
  *
  * @param dataset the dataset (<code>null</code> permitted).
  * @return The range (<code>null</code> if the dataset is <code>null</code> or empty).
  * @see #findRangeBounds(XYDataset)
  */
 public Range findDomainBounds(XYDataset dataset) {
   if (dataset == null) {
     return null;
   }
   Range r = DatasetUtilities.findDomainBounds(dataset, false);
   if (r == null) {
     return null;
   }
   return new Range(
       r.getLowerBound() + this.xOffset, r.getUpperBound() + this.blockWidth + this.xOffset);
 }
 /**
  * Returns the range of values the renderer requires to display all the items from the specified
  * dataset.
  *
  * @param dataset the dataset (<code>null</code> permitted).
  * @return The range (<code>null</code> if the dataset is <code>null</code> or empty).
  */
 public Range findRangeBounds(XYDataset dataset) {
   if (dataset == null) {
     return null;
   }
   Range r = DatasetUtilities.findRangeBounds(dataset, false);
   if (r == null) {
     return null;
   }
   double offset = 0; // TODO getSeriesShape(n).getBounds().height / 2;
   return new Range(r.getLowerBound() + offset, r.getUpperBound() + offset);
 }
Example #11
0
  /**
   * 创建一个数据集
   *
   * @return
   */
  private CategoryDataset getCategoryDataset() {

    DefaultKeyedValues keyedValues = new DefaultKeyedValues();
    keyedValues.addValue("1月", 310);
    keyedValues.addValue("2月", 489);
    keyedValues.addValue("3月", 512);
    keyedValues.addValue("4月", 589);
    keyedValues.addValue("5月", 359);
    keyedValues.addValue("6月", 402);
    CategoryDataset dataset = DatasetUtilities.createCategoryDataset("java book", keyedValues);
    return dataset;
  }
 /**
  * Returns the range of the values in the dataset's domain, including or excluding the interval
  * around each x-value as specified.
  *
  * @param includeInterval a flag that determines whether or not the x-interval should be taken
  *     into account.
  * @return The range.
  */
 @Override
 public Range getDomainBounds(boolean includeInterval) {
   // first get the range without the interval, then expand it for the
   // interval width
   Range range = DatasetUtilities.findDomainBounds(this.dataset, false);
   if (includeInterval && range != null) {
     double lowerAdj = getIntervalWidth() * getIntervalPositionFactor();
     double upperAdj = getIntervalWidth() - lowerAdj;
     range = new Range(range.getLowerBound() - lowerAdj, range.getUpperBound() + upperAdj);
   }
   return range;
 }
Example #13
0
 /**
  * Creates a sample dataset.
  *
  * @return A sample dataset.
  */
 private CategoryDataset createDataset() {
   final double[][] data =
       new double[][] {
         {3.0, 4.0, 3.0, 5.0},
         {5.0, 7.0, 6.0, 8.0},
         {5.0, 7.0, 3.0, 8.0},
         {1.0, 2.0, 3.0, 4.0},
         {2.0, 3.0, 2.0, 3.0}
       };
   final CategoryDataset dataset =
       DatasetUtilities.createCategoryDataset("Region ", "Sales/Q", data);
   return dataset;
 }
 /**
  * Returns the range of values the renderer requires to display all the items from the specified
  * dataset.
  *
  * @param dataset the dataset (<code>null</code> permitted).
  * @return The range (<code>null</code> if the dataset is <code>null</code> or empty).
  * @see #findDomainBounds(XYDataset)
  */
 public Range findRangeBounds(XYDataset dataset) {
   if (dataset != null) {
     Range r = DatasetUtilities.findRangeBounds(dataset, false);
     if (r == null) {
       return null;
     } else {
       return new Range(
           r.getLowerBound() + this.yOffset, r.getUpperBound() + this.blockHeight + this.yOffset);
     }
   } else {
     return null;
   }
 }
Example #15
0
  /**
   * 创建一个数据集
   *
   * @return
   */
  private CategoryDataset getCategoryDataset() {

    DefaultKeyedValues keyedValues = new DefaultKeyedValues();
    keyedValues.addValue("1", 310);
    keyedValues.addValue("2", 489);
    keyedValues.addValue("3", 512);
    keyedValues.addValue("4", 589);
    keyedValues.addValue("5", 359);
    keyedValues.addValue("6", 402);
    // 排序
    keyedValues.sortByValues(SortOrder.ASCENDING);
    CategoryDataset dataset = DatasetUtilities.createCategoryDataset("JAVA图书", keyedValues);

    return dataset;
  }
Example #16
0
 private XYIntervalSeries computeAcceptableDeviationData(double lowerBound, double upperBound) {
   final XYSeries identity =
       DatasetUtilities.sampleFunction2DToSeries(x -> x, lowerBound, upperBound, 100, "1:1 line");
   final XYIntervalSeries xyIntervalSeries = new XYIntervalSeries(identity.getKey());
   for (int i = 0; i < identity.getItemCount(); i++) {
     XYDataItem item = identity.getDataItem(i);
     final double x = item.getXValue();
     final double y = item.getYValue();
     if (scatterPlotModel.showAcceptableDeviation) {
       final double acceptableDeviation = scatterPlotModel.acceptableDeviationInterval;
       final double xOff = acceptableDeviation * x / 100;
       final double yOff = acceptableDeviation * y / 100;
       xyIntervalSeries.add(x, x - xOff, x + xOff, y, y - yOff, y + yOff);
     } else {
       xyIntervalSeries.add(x, x, x, y, y, y);
     }
   }
   return xyIntervalSeries;
 }
Example #17
0
 private XYIntervalSeries computeRegressionData(double xStart, double xEnd) {
   if (scatterpointsDataset.getItemCount(0) > 1) {
     final double[] coefficients = Regression.getOLSRegression(scatterpointsDataset, 0);
     final Function2D curve = new LineFunction2D(coefficients[0], coefficients[1]);
     final XYSeries regressionData =
         DatasetUtilities.sampleFunction2DToSeries(curve, xStart, xEnd, 100, "regression line");
     final XYIntervalSeries xyIntervalRegression = new XYIntervalSeries(regressionData.getKey());
     for (int i = 0; i < regressionData.getItemCount(); i++) {
       XYDataItem item = regressionData.getDataItem(i);
       final double x = item.getXValue();
       final double y = item.getYValue();
       xyIntervalRegression.add(x, x, x, y, y, y);
     }
     return xyIntervalRegression;
   } else {
     JOptionPane.showMessageDialog(
         this,
         "Unable to compute regression line.\n"
             + "At least 2 values are needed to compute regression coefficients.");
     return null;
   }
 }
  /**
   * Create a bar chart with sample data in the range -3 to +3.
   *
   * @return The chart.
   */
  private static JFreeChart createWaterfallChart() {

    // create a dataset...
    Number[][] data =
        new Integer[][] {
          {new Integer(-3), new Integer(-2)},
          {new Integer(-1), new Integer(1)},
          {new Integer(2), new Integer(3)}
        };

    CategoryDataset dataset = DatasetUtilities.createCategoryDataset("S", "C", data);

    // create the chart...
    return ChartFactory.createWaterfallChart(
        "Waterfall Chart",
        "Domain",
        "Range",
        dataset,
        PlotOrientation.HORIZONTAL,
        true, // include legend
        true,
        true);
  }
Example #19
0
  /**
   * Starting point for the demo.
   *
   * @param args ignored.
   */
  public static void main(final String[] args) {

    // create a chart
    final double[][] data =
        new double[][] {
          {56.0, -12.0, 34.0, 76.0, 56.0, 100.0, 67.0, 45.0},
          {37.0, 45.0, 67.0, 25.0, 34.0, 34.0, 100.0, 53.0},
          {43.0, 54.0, 34.0, 34.0, 87.0, 64.0, 73.0, 12.0}
        };
    final CategoryDataset dataset =
        DatasetUtilities.createCategoryDataset("Series ", "Type ", data);

    JFreeChart chart = null;
    final boolean drilldown = true;

    if (drilldown) {
      final CategoryAxis categoryAxis = new CategoryAxis("Category");
      final ValueAxis valueAxis = new NumberAxis("Value");
      final BarRenderer renderer = new BarRenderer();
      renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
      renderer.setItemURLGenerator(new StandardCategoryURLGenerator("bar_chart_detail.jsp"));
      final CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer);
      plot.setOrientation(PlotOrientation.VERTICAL);
      chart = new JFreeChart("Bar Chart", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
      chart =
          ChartFactory.createBarChart(
              "Vertical Bar Chart", // chart title
              "Category", // domain axis label
              "Value", // range axis label
              dataset, // data
              PlotOrientation.VERTICAL,
              true, // include legend
              true,
              false);
    }
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    *
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
      final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      final File file1 = new File("barchart100.png");
      ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

      // write an HTML page incorporating the image with an image map
      final File file2 = new File("barchart100.html");
      final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
      final PrintWriter writer = new PrintWriter(out);
      writer.println("<HTML>");
      writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
      writer.println("<BODY>");
      ChartUtilities.writeImageMap(writer, "chart", info, true);
      writer.println(
          "<IMG SRC=\"barchart100.png\" "
              + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
      writer.println("</BODY>");
      writer.println("</HTML>");
      writer.close();

    } catch (IOException e) {
      System.out.println(e.toString());
    }
  }
  /**
   * Draws the plot on a Java 2D graphics device (such as the screen or a printer).
   *
   * @param g2 the graphics device.
   * @param area the area within which the plot should be drawn.
   * @param anchor the anchor point (<code>null</code> permitted).
   * @param parentState the state from the parent plot, if there is one.
   * @param info collects info about the drawing.
   */
  public void draw(
      Graphics2D g2,
      Rectangle2D area,
      Point2D anchor,
      PlotState parentState,
      PlotRenderingInfo info) {

    // adjust the drawing area for the plot insets (if any)...
    RectangleInsets insets = getInsets();
    insets.trim(area);
    drawBackground(g2, area);
    drawOutline(g2, area);

    // check that there is some data to display...
    if (DatasetUtilities.isEmptyOrNull(getDataset())) {
      drawNoDataMessage(g2, area);
      return;
    }

    int pieCount = 0;
    if (getDataExtractOrder() == TableOrder.BY_ROW) {
      pieCount = getDataset().getRowCount();
    } else {
      pieCount = getDataset().getColumnCount();
    }

    // the columns variable is always >= rows
    int displayCols = (int) Math.ceil(Math.sqrt(pieCount));
    int displayRows = (int) Math.ceil((double) pieCount / (double) displayCols);

    // swap rows and columns to match plotArea shape
    if (displayCols > displayRows && area.getWidth() < area.getHeight()) {
      int temp = displayCols;
      displayCols = displayRows;
      displayRows = temp;
    }

    prefetchSectionPaints();

    int x = (int) area.getX();
    int y = (int) area.getY();
    int width = ((int) area.getWidth()) / displayCols;
    int height = ((int) area.getHeight()) / displayRows;
    int row = 0;
    int column = 0;
    int diff = (displayRows * displayCols) - pieCount;
    int xoffset = 0;
    Rectangle rect = new Rectangle();

    for (int pieIndex = 0; pieIndex < pieCount; pieIndex++) {
      rect.setBounds(x + xoffset + (width * column), y + (height * row), width, height);

      String title = null;
      if (getDataExtractOrder() == TableOrder.BY_ROW) {
        title = getDataset().getRowKey(pieIndex).toString();
      } else {
        title = getDataset().getColumnKey(pieIndex).toString();
      }
      getPieChart().setTitle(title);

      PieDataset piedataset = null;
      PieDataset dd = new CategoryToPieDataset(getDataset(), getDataExtractOrder(), pieIndex);
      if (getLimit() > 0.0) {
        piedataset =
            DatasetUtilities.createConsolidatedPieDataset(dd, getAggregatedItemsKey(), getLimit());
      } else {
        piedataset = dd;
      }
      PiePlot piePlot = (PiePlot) getPieChart().getPlot();
      piePlot.setDataset(piedataset);
      piePlot.setPieIndex(pieIndex);

      // update the section colors to match the global colors...
      for (int i = 0; i < piedataset.getItemCount(); i++) {
        Comparable key = piedataset.getKey(i);
        Paint p;
        if (key.equals(getAggregatedItemsKey())) {
          p = getAggregatedItemsPaint();
        } else {
          p = (Paint) this.sectionPaints.get(key);
        }
        piePlot.setSectionPaint(key, p);
      }

      ChartRenderingInfo subinfo = null;
      if (info != null) {
        subinfo = new ChartRenderingInfo();
      }
      getPieChart().draw(g2, rect, subinfo);
      if (info != null) {
        info.getOwner().getEntityCollection().addAll(subinfo.getEntityCollection());
        info.addSubplotInfo(subinfo.getPlotInfo());
      }

      ++column;
      if (column == displayCols) {
        column = 0;
        ++row;

        if (row == displayRows - 1 && diff != 0) {
          xoffset = (diff * width) / 2;
        }
      }
    }
  }
 /**
  * Returns the range of values the renderer requires to display all the items from the specified
  * dataset.
  *
  * @param dataset the dataset (<code>null</code> permitted).
  * @return The range (or <code>null</code> if the dataset is <code>null</code> or empty).
  */
 public Range findRangeBounds(CategoryDataset dataset) {
   return DatasetUtilities.findRangeBounds(dataset);
 }
Example #22
0
  protected void onDataChange() {
    XYPlot plot = chartPanel.getChart().getXYPlot();

    if (data != DEFAULT_DATA) {
      DescriptiveStatistics stats = new DescriptiveStatistics(new DataBlock(data));

      double m = 0, M = 0, dv = 1;
      if (adjustDistribution && distribution != DEFAULT_DISTRIBUTION) {
        m = stats.getAverage();
        M = distribution.getExpectation();
        double v = stats.getVar();
        double V = distribution.getVariance();
        dv = Math.sqrt(v / V);
      }

      final double xmin = stats.getMin() < lBound ? stats.getMin() : lBound;
      final double xmax = stats.getMax() > rBound ? stats.getMax() : rBound;
      final int n = hCount != 0 ? hCount : (int) Math.ceil(Math.sqrt(stats.getObservationsCount()));
      final double xstep = (xmax - xmin) / n;

      // distribution >
      if (distribution != DEFAULT_DISTRIBUTION) {
        Function2D density =
            new Function2D() {
              @Override
              public double getValue(double x) {
                return distribution.getDensity(x);
              }
            };

        final double zmin =
            distribution.hasLeftBound() != BoundaryType.None
                ? distribution.getLeftBound()
                : ((xmin - xstep - m) / dv + M);
        final double zmax =
            distribution.hasRightBound() != BoundaryType.None
                ? distribution.getRightBound()
                : ((xmax + xstep - m) / dv + M);

        // TODO: create IDistribution#getName() method
        String name = distribution.getClass().getSimpleName();

        ((XYLineAndShapeRenderer) plot.getRenderer(DISTRIBUTION_INDEX))
            .setLegendItemToolTipGenerator(getTooltipGenerator(distribution));
        plot.setDataset(
            DISTRIBUTION_INDEX, DatasetUtilities.sampleFunction2D(density, zmin, zmax, n, name));
      } else {
        plot.setDataset(DISTRIBUTION_INDEX, Charts.emptyXYDataset());
      }
      // < distribution

      // histogram >
      XYSeries hSeries = new XYSeries("");
      double nobs = stats.getObservationsCount();
      for (int i = 0; i <= n; ++i) {
        double x0 = xmin + i * xstep;
        double x1 = x0 + xstep;
        double y = stats.countBetween(x0, x1) / (nobs * xstep / dv);
        hSeries.add(((x0 + x1) / 2 - m) / dv + M, y);
      }

      plot.setDataset(
          HISTOGRAM_INDEX, new XYBarDataset(new XYSeriesCollection(hSeries), xstep / dv + M));
      // < histogram
    } else {
      plot.setDataset(HISTOGRAM_INDEX, Charts.emptyXYDataset());
      plot.setDataset(DISTRIBUTION_INDEX, Charts.emptyXYDataset());
    }

    onColorSchemeChange();
  }
Example #23
0
  public static String getSimpleBarChart(Map dataSource, String objectName, HttpSession session)
      throws Throwable {
    Element chartObject =
        XMLHandler.getElementByAttribute(getChartObjectList(), "name", objectName);

    List invokeFields = chartObject.getChild("InvokeFields").getChildren("Field");
    double[][] data = new double[invokeFields.size()][dataSource.size()];
    String[] rowKeys = new String[invokeFields.size()];
    String[] columnKeys = new String[dataSource.size()];
    String columnLabel = chartObject.getChildText("ColumnLabel");

    for (int i = 0; i < dataSource.size(); i++) {
      Map rec = (Map) dataSource.get("ROW" + i);
      columnKeys[i] = DataFilter.show(rec, columnLabel);
      for (int j = 0; j < invokeFields.size(); j++) {
        data[j][i] =
            Double.parseDouble(
                rec.get(((Element) invokeFields.get(j)).getAttributeValue("name")).toString());
      }
    }
    for (int i = 0; i < invokeFields.size(); i++) {
      rowKeys[i] = ((Element) invokeFields.get(i)).getAttributeValue("label");
    }

    CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);

    PlotOrientation plotOrientation =
        chartObject.getAttributeValue("plotOrientation").equalsIgnoreCase("VERTICAL")
            ? PlotOrientation.VERTICAL
            : PlotOrientation.HORIZONTAL;
    JFreeChart chart =
        ChartFactory.createBarChart3D(
            chartObject.getAttributeValue("title"),
            chartObject.getAttributeValue("categoryAxisLabel"),
            chartObject.getAttributeValue("valueAxisLabel"),
            dataset,
            plotOrientation,
            chartObject.getAttribute("showLegend").getBooleanValue(),
            chartObject.getAttribute("showToolTips").getBooleanValue(),
            chartObject.getAttribute("urls").getBooleanValue());

    CategoryPlot C3dplot = (CategoryPlot) chart.getPlot();
    if (chartObject.getAttribute("alpha") != null) {
      C3dplot.setForegroundAlpha(chartObject.getAttribute("alpha").getFloatValue());
    }

    BarRenderer3D barrenderer = (BarRenderer3D) C3dplot.getRenderer();
    barrenderer.setLabelGenerator(new StandardCategoryLabelGenerator());
    barrenderer.setItemLabelsVisible(true);
    barrenderer.setPositiveItemLabelPosition(
        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BASELINE_CENTER));

    int width, height;
    if (chartObject.getAttributeValue("width").equalsIgnoreCase("auto")) {
      width = (50 * dataSource.size()) * invokeFields.size() + 100;
    } else {
      width = Integer.parseInt(chartObject.getAttributeValue("width"));
    }
    if (chartObject.getAttributeValue("height").equalsIgnoreCase("auto")) {
      height = (50 * dataSource.size()) * invokeFields.size() + 100;
    } else {
      height = Integer.parseInt(chartObject.getAttributeValue("height"));
    }

    return ServletUtilities.saveChartAsPNG(chart, width, height, session);
  }
Example #24
0
  public static String getBarSeries(Map dataSource, String objectName, HttpSession session)
      throws Exception {
    DefaultKeyedValues barValues = new DefaultKeyedValues();
    DefaultKeyedValues seriesValues = new DefaultKeyedValues();
    Element chartObject =
        XMLHandler.getElementByAttribute(getChartObjectList(), "name", objectName);

    Element barField = chartObject.getChild("BarFields").getChild("Field");
    Element seriesField = chartObject.getChild("SeriesFields").getChild("Field");

    for (int i = 0; i < dataSource.size(); i++) {
      Map rec = (Map) dataSource.get("ROW" + i);
      barValues.addValue(
          DataFilter.show(rec, chartObject.getChildText("ColumnLabel")),
          Double.parseDouble(rec.get(barField.getAttributeValue("name")).toString()));
      seriesValues.addValue(
          DataFilter.show(rec, chartObject.getChildText("ColumnLabel")),
          Double.parseDouble(rec.get(seriesField.getAttributeValue("name")).toString()));
    }

    CategoryDataset dataset =
        DatasetUtilities.createCategoryDataset(barField.getAttributeValue("label"), barValues);

    PlotOrientation plotOrientation =
        chartObject.getAttributeValue("plotOrientation").equalsIgnoreCase("VERTICAL")
            ? PlotOrientation.VERTICAL
            : PlotOrientation.HORIZONTAL;
    JFreeChart chart =
        ChartFactory.createBarChart3D(
            chartObject.getAttributeValue("title"),
            chartObject.getAttributeValue("categoryAxisLabel"),
            chartObject.getAttributeValue("valueAxisLabel"),
            dataset,
            plotOrientation,
            chartObject.getAttribute("showLegend").getBooleanValue(),
            chartObject.getAttribute("showToolTips").getBooleanValue(),
            chartObject.getAttribute("urls").getBooleanValue());

    CategoryPlot categoryplot = chart.getCategoryPlot();
    LineRenderer3D lineRenderer = new LineRenderer3D();
    CategoryDataset datasetSeries =
        DatasetUtilities.createCategoryDataset(
            seriesField.getAttributeValue("label"), seriesValues);

    categoryplot.setDataset(1, datasetSeries);
    categoryplot.setRangeAxis(1, new NumberAxis3D(seriesField.getAttributeValue("label")));
    categoryplot.setRenderer(1, lineRenderer);
    categoryplot.mapDatasetToRangeAxis(1, 1);

    BarRenderer3D barrenderer = (BarRenderer3D) categoryplot.getRenderer();
    barrenderer.setLabelGenerator(new StandardCategoryLabelGenerator());
    barrenderer.setItemLabelsVisible(true);
    barrenderer.setPositiveItemLabelPosition(
        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BASELINE_CENTER));

    //	        lineRenderer.setLabelGenerator(new StandardCategoryLabelGenerator());
    //	        lineRenderer.setItemLabelsVisible(true);
    //	        lineRenderer.setPositiveItemLabelPosition(
    //	                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.CENTER));

    float alpha = 0.7F;
    if (chartObject.getAttribute("alpha") != null) {
      alpha = chartObject.getAttribute("alpha").getFloatValue();
    }
    categoryplot.setForegroundAlpha(alpha);

    int width, height;
    if (chartObject.getAttributeValue("width").equalsIgnoreCase("auto")) {
      width = (50 * dataSource.size()) + 100;
    } else {
      width = Integer.parseInt(chartObject.getAttributeValue("width"));
    }
    if (chartObject.getAttributeValue("height").equalsIgnoreCase("auto")) {
      height = (50 * dataSource.size()) + 100;
    } else {
      height = Integer.parseInt(chartObject.getAttributeValue("height"));
    }

    return ServletUtilities.saveChartAsPNG(chart, width, height, session);
  }
  /**
   * Draws the visual representation of a single data item.
   *
   * @param g2 the graphics device.
   * @param state the renderer state.
   * @param dataArea the area within which the plot is being drawn.
   * @param info collects information about the drawing.
   * @param plot the plot (can be used to obtain standard color information etc).
   * @param domainAxis the domain axis.
   * @param rangeAxis the range axis.
   * @param dataset the dataset.
   * @param series the series index (zero-based).
   * @param item the item index (zero-based).
   * @param crosshairState crosshair information for the plot (<code>null</code> permitted).
   * @param pass the pass index.
   */
  public void drawItem(
      Graphics2D g2,
      XYItemRendererState state,
      Rectangle2D dataArea,
      PlotRenderingInfo info,
      XYPlot plot,
      ValueAxis domainAxis,
      ValueAxis rangeAxis,
      XYDataset dataset,
      int series,
      int item,
      CrosshairState crosshairState,
      int pass) {

    if (!(dataset instanceof IntervalXYDataset && dataset instanceof TableXYDataset)) {
      String message = "dataset (type " + dataset.getClass().getName() + ") has wrong type:";
      boolean and = false;
      if (!IntervalXYDataset.class.isAssignableFrom(dataset.getClass())) {
        message += " it is no IntervalXYDataset";
        and = true;
      }
      if (!TableXYDataset.class.isAssignableFrom(dataset.getClass())) {
        if (and) {
          message += " and";
        }
        message += " it is no TableXYDataset";
      }

      throw new IllegalArgumentException(message);
    }

    IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset;
    double value = intervalDataset.getYValue(series, item);
    if (Double.isNaN(value)) {
      return;
    }

    // if we are rendering the values as percentages, we need to calculate
    // the total for the current item.  Unfortunately here we end up
    // repeating the calculation more times than is strictly necessary -
    // hopefully I'll come back to this and find a way to add the
    // total(s) to the renderer state.  The other problem is we implicitly
    // assume the dataset has no negative values...perhaps that can be
    // fixed too.
    double total = 0.0;
    if (this.renderAsPercentages) {
      total = DatasetUtilities.calculateStackTotal((TableXYDataset) dataset, item);
      value = value / total;
    }

    double positiveBase = 0.0;
    double negativeBase = 0.0;

    for (int i = 0; i < series; i++) {
      double v = dataset.getYValue(i, item);
      if (!Double.isNaN(v)) {
        if (this.renderAsPercentages) {
          v = v / total;
        }
        if (v > 0) {
          positiveBase = positiveBase + v;
        } else {
          negativeBase = negativeBase + v;
        }
      }
    }

    double translatedBase;
    double translatedValue;
    RectangleEdge edgeR = plot.getRangeAxisEdge();
    if (value > 0.0) {
      translatedBase = rangeAxis.valueToJava2D(positiveBase, dataArea, edgeR);
      translatedValue = rangeAxis.valueToJava2D(positiveBase + value, dataArea, edgeR);
    } else {
      translatedBase = rangeAxis.valueToJava2D(negativeBase, dataArea, edgeR);
      translatedValue = rangeAxis.valueToJava2D(negativeBase + value, dataArea, edgeR);
    }

    RectangleEdge edgeD = plot.getDomainAxisEdge();
    double startX = intervalDataset.getStartXValue(series, item);
    if (Double.isNaN(startX)) {
      return;
    }
    double translatedStartX = domainAxis.valueToJava2D(startX, dataArea, edgeD);

    double endX = intervalDataset.getEndXValue(series, item);
    if (Double.isNaN(endX)) {
      return;
    }
    double translatedEndX = domainAxis.valueToJava2D(endX, dataArea, edgeD);

    double translatedWidth = Math.max(1, Math.abs(translatedEndX - translatedStartX));
    double translatedHeight = Math.abs(translatedValue - translatedBase);
    if (getMargin() > 0.0) {
      double cut = translatedWidth * getMargin();
      translatedWidth = translatedWidth - cut;
      translatedStartX = translatedStartX + cut / 2;
    }

    Rectangle2D bar = null;
    PlotOrientation orientation = plot.getOrientation();
    if (orientation == PlotOrientation.HORIZONTAL) {
      bar =
          new Rectangle2D.Double(
              Math.min(translatedBase, translatedValue),
              Math.min(translatedEndX, translatedStartX),
              translatedHeight,
              translatedWidth);
    } else if (orientation == PlotOrientation.VERTICAL) {
      bar =
          new Rectangle2D.Double(
              Math.min(translatedStartX, translatedEndX),
              Math.min(translatedBase, translatedValue),
              translatedWidth,
              translatedHeight);
    }
    boolean positive = (value > 0.0);
    boolean inverted = rangeAxis.isInverted();
    RectangleEdge barBase;
    if (orientation == PlotOrientation.HORIZONTAL) {
      if (positive && inverted || !positive && !inverted) {
        barBase = RectangleEdge.RIGHT;
      } else {
        barBase = RectangleEdge.LEFT;
      }
    } else {
      if (positive && !inverted || !positive && inverted) {
        barBase = RectangleEdge.BOTTOM;
      } else {
        barBase = RectangleEdge.TOP;
      }
    }

    if (pass == 0) {
      if (getShadowsVisible()) {
        getBarPainter().paintBarShadow(g2, this, series, item, bar, barBase, false);
      }
    } else if (pass == 1) {
      getBarPainter().paintBar(g2, this, series, item, bar, barBase);

      // add an entity for the item...
      if (info != null) {
        EntityCollection entities = info.getOwner().getEntityCollection();
        if (entities != null) {
          addEntity(entities, bar, dataset, series, item, bar.getCenterX(), bar.getCenterY());
        }
      }
    } else if (pass == 2) {
      // handle item label drawing, now that we know all the bars have
      // been drawn...
      if (isItemLabelVisible(series, item)) {
        XYItemLabelGenerator generator = getItemLabelGenerator(series, item);
        drawItemLabel(g2, dataset, series, item, plot, generator, bar, value < 0.0);
      }
    }
  }