List of usage examples for org.jfree.chart.entity StandardEntityCollection StandardEntityCollection
public StandardEntityCollection()
From source file:org.gephi.statistics.plugin.DegreeDistribution.java
/** * * @return The undirected version of this report. *//*from w w w .j a va 2 s .c o m*/ private String getUndirectedReport() { double max = 0; XYSeries series2 = new XYSeries("Series 2"); for (int i = 1; i < combinedDistribution[1].length; i++) { if (combinedDistribution[1][i] > 0) { series2.add((Math.log(combinedDistribution[0][i]) / Math.log(Math.E)), (Math.log(combinedDistribution[1][i]) / Math.log(Math.E))); max = (float) Math.max((Math.log(combinedDistribution[0][i]) / Math.log(Math.E)), max); } } double a = combinedAlpha; double b = combinedBeta; XYSeries series1 = new XYSeries(combinedAlpha + " "); series1.add(0, a); series1.add(max, a + b * max); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series1); dataset.addSeries(series2); JFreeChart chart = ChartFactory.createXYLineChart("Degree Distribution", "Degree", "Occurrence", dataset, PlotOrientation.VERTICAL, true, false, false); XYPlot plot = (XYPlot) chart.getPlot(); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); renderer.setSeriesLinesVisible(0, true); renderer.setSeriesShapesVisible(0, false); renderer.setSeriesLinesVisible(1, false); renderer.setSeriesShapesVisible(1, true); renderer.setSeriesShape(1, new java.awt.geom.Ellipse2D.Double(0, 0, 1, 1)); plot.setBackgroundPaint(java.awt.Color.WHITE); plot.setDomainGridlinePaint(java.awt.Color.GRAY); plot.setRangeGridlinePaint(java.awt.Color.GRAY); plot.setRenderer(renderer); String imageFile = ""; try { final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); TempDir tempDir = TempDirUtils.createTempDir(); final String fileName = "distribution.png"; final File file1 = tempDir.createFile(fileName); imageFile = "<IMG SRC=\"file:" + file1.getAbsolutePath() + "\" " + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\"></IMG>"; ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info); } catch (IOException e) { System.out.println(e.toString()); } String report = "<HTML> <BODY> <h1>Degree Distribution Metric Report </h1> " + "<hr>" + "<br>" + "<h2> Parameters: </h2>" + "Network Interpretation: " + (isDirected ? "directed" : "undirected") + "<br>" + "<br> <h2> Results: </h2>" + "Degree Power Law: -" + combinedAlpha + "\n <BR>" + imageFile + "</BODY> </HTML>"; return report; }
From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.StatisticJspBean.java
/** * write in the http response the statistic graph of all response submit who * verify the date filter./*from w ww.j a v a2 s . com*/ * * @param request the http request * @param response The http response */ public void doGenerateGraph(HttpServletRequest request, HttpServletResponse response) { Locale locale = getLocale(); String strFistResponseDateFilter = request.getParameter(PARAMETER_FIRST_RESPONSE_DATE_FILTER); String strLastResponseDateFilter = request.getParameter(PARAMETER_LAST_RESPONSE_DATE_FILTER); String strTimesUnit = request.getParameter(PARAMETER_TIMES_UNIT); String strTypeData = request.getParameter(PARAMETER_TYPE_DATA); List<ResultStatistic> listeResultStatistic = null; if (strTypeData.equals(CONSTANT_PRODUCT_TYPE)) { listeResultStatistic = _serviceStatistic.getProductStatistic(strTimesUnit, strFistResponseDateFilter, strLastResponseDateFilter); } else { listeResultStatistic = _serviceStatistic.getPurchaseStatistic(strTimesUnit, strFistResponseDateFilter, strLastResponseDateFilter); } String strNumberOfResponseAxisX = AppPropertiesService.getProperty(PROPERTY_NUMBER_RESPONSE_AXIS_X); int nNumberOfResponseAxisX = 10; try { nNumberOfResponseAxisX = Integer.parseInt(strNumberOfResponseAxisX); } catch (NumberFormatException ne) { AppLogService.error(ne); } List<ResultStatistic> listStatisticGraph = new ArrayList<ResultStatistic>(); ResultStatistic statisticFormSubmit; if (listeResultStatistic.size() != 0) { for (int cpt = 0; cpt < nNumberOfResponseAxisX; cpt++) { statisticFormSubmit = new ResultStatistic(); statisticFormSubmit.setNumberResponse(0); statisticFormSubmit.setStatisticDate(StatisticService .addStatisticInterval(listeResultStatistic.get(0).getStatisticDate(), strTimesUnit, cpt)); listStatisticGraph.add(statisticFormSubmit); } } for (ResultStatistic statisticFormSubmitGraph : listStatisticGraph) { for (ResultStatistic resultStatistic : listeResultStatistic) { if (StatisticService.sameDate(statisticFormSubmitGraph.getStatisticDate(), resultStatistic.getStatisticDate(), strTimesUnit)) { statisticFormSubmitGraph.setNumberResponse(resultStatistic.getNumberResponse()); } } } String strLabelAxisX = I18nService.getLocalizedString(PROPERTY_LABEL_AXIS_X, locale); String strLabelAxisY; if (strTypeData.equals(CONSTANT_PRODUCT_TYPE)) { strLabelAxisY = I18nService.getLocalizedString(PROPERTY_LABEL_AXIS_Y_PRODUCT, locale); } else { strLabelAxisY = I18nService.getLocalizedString(PROPERTY_LABEL_AXIS_Y_PURCHASE, locale); } try { JFreeChart chart = StatisticService.createXYGraph(listStatisticGraph, strLabelAxisX, strLabelAxisY, strTimesUnit); ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); BufferedImage chartImage = chart.createBufferedImage(600, 200, info); response.setContentType(CONTENT_TYPE_IMAGE_PNG); PngEncoder encoder = new PngEncoder(chartImage, false, 0, 9); response.getOutputStream().write(encoder.pngEncode()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { AppLogService.error(e); } }
From source file:gov.nih.nci.cma.web.graphing.GEPlot.java
public String generateGeometricMeanIntensityChart(String xAxisLabel, String yAxisLabel, HttpSession session, PrintWriter pw) {/*from www .jav a2 s .c om*/ String gmfilename = ""; JFreeChart gmChart = null; try { gmChart = ChartFactory.createBarChart(null, xAxisLabel, // domain axis label yAxisLabel, gmDataset, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips? false // URLs? ); gmChart.setBackgroundPaint(java.awt.Color.white); // lets start some customization to retro fit w/jcharts lookand feel CategoryPlot plot = gmChart.getCategoryPlot(); CategoryAxis axis = plot.getDomainAxis(); axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45); axis.setLowerMargin(0.02); // two percent axis.setCategoryMargin(0.20); // 20 percent axis.setUpperMargin(0.02); // two percent //StatisticalBarRenderer renderer = new StatisticalBarRenderer(); BarRenderer renderer = (BarRenderer) plot.getRenderer(); // BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setItemMargin(0.01); // one percent renderer.setDrawBarOutline(true); renderer.setOutlinePaint(Color.BLACK); renderer.setBaseToolTipGenerator(new CategoryToolTipGenerator() { public String generateToolTip(CategoryDataset dataset, int series, int item) { String stdDev = (String) stdDevMap .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item)); return "Probeset : " + dataset.getRowKey(series) + "<br/>Intensity : " + new DecimalFormat("0.0000").format(dataset.getValue(series, item)) + "<br/>" + "<br/>Std. Dev.: " + stdDev + "<br/>"; } }); plot.setRenderer(renderer); gmChart.removeLegend(); ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); //gmfilename = ServletUtilities.saveChartAsPNG(gmChart, imgW, 400, info, session); gmfilename = ServletUtilities.saveChartAsPNG(gmChart, imgW, 400, info, session); ChartUtilities.writeImageMap(pw, gmfilename, info, new CustomOverlibToolTipTagFragmentGenerator(), new StandardURLTagFragmentGenerator()); } catch (Exception e) { System.out.println("Exception - " + e.toString()); e.printStackTrace(System.out); } return gmfilename; }
From source file:com.modeln.build.ctrl.charts.CMnBuildListChart.java
/** * Return rendering information for the chart. *//*from ww w . java 2 s .co m*/ public static final ChartRenderingInfo getAverageAreaTestCountRenderingInfo() { return new ChartRenderingInfo(new StandardEntityCollection()); }
From source file:org.yardstickframework.report.jfreechart.JFreeChartGraphPlotter.java
/** * @param folderToWrite Folder to write the resulted charts. * @param plots Collections of plots.// ww w. ja va 2 s .co m * @param infoMap Map with additional plot info. * @param mode Generation mode. * @throws Exception If failed. */ private static void processPlots(File folderToWrite, Collection<List<PlotData>> plots, Map<String, List<JFreeChartPlotInfo>> infoMap, JFreeChartGenerationMode mode) throws Exception { ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false); int idx = -1; while (true) { idx++; DefaultXYDataset dataSet = new DefaultXYDataset(); List<JFreeChartPlotInfo> infoList = new ArrayList<>(); String xAxisLabel = ""; String yAxisLabel = ""; String plotName = ""; int cnt = 0; for (List<PlotData> plotData0 : plots) { if (plotData0.size() <= idx) continue; PlotData plotData = plotData0.get(idx); dataSet.addSeries(plotData.plotName() + "_" + cnt++, plotData.series().data); xAxisLabel = plotData.xAxisLabel; yAxisLabel = plotData.yAxisLabel; plotName = plotData.plotName(); infoList.add(info(plotData.series(), mode)); } if (infoList.isEmpty()) break; JFreeChart chart = ChartFactory.createXYLineChart("", xAxisLabel, yAxisLabel, dataSet, PlotOrientation.VERTICAL, false, false, false); AxisSpace as = new AxisSpace(); as.add(150, RectangleEdge.LEFT); XYPlot plot = (XYPlot) chart.getPlot(); BasicStroke stroke = new BasicStroke(1); plot.setRenderer(renderer); plot.setBackgroundPaint(WHITE); plot.setRangeGridlinePaint(GRAY); plot.setDomainGridlinePaint(GRAY); plot.setFixedRangeAxisSpace(as); plot.setOutlineStroke(stroke); for (int i = 0; i < infoList.size(); i++) { Color color = PLOT_COLORS[i % PLOT_COLORS.length]; renderer.setSeriesPaint(i, color); renderer.setSeriesStroke(i, new BasicStroke(3)); // Line thickness. infoList.get(i).color(Integer.toHexString(color.getRGB()).substring(2)); } ValueAxis axis = plot.getRangeAxis(); Font font = new Font("Helvetica,Arial,sans-serif", Font.BOLD, axis.getTickLabelFont().getSize() + 5); axis.setTickLabelFont(font); axis.setLabelFont(font); plot.getDomainAxis().setTickLabelFont(font); plot.getDomainAxis().setLabelFont(font); chart.setTitle(new TextTitle(yAxisLabel, new Font(font.getName(), font.getStyle(), 30))); File res = new File(folderToWrite, plotName + ".png"); ChartUtilities.saveChartAsPNG(res, chart, 1000, 500, info); infoMap.put(res.getAbsolutePath(), infoList); println("Chart is saved to file: ", res); } }
From source file:com.tonbeller.jpivot.chart.ChartComponent.java
/** * Entry point for producing charts, called by wcf render tag. * Produces a jfreechart dataset from olap model, then creates a chart and * writes it to the servlet container temp directory. * Returns a DOM document for Renderer to transform into html. * Requires that jfreechart servlet is installed in this application context. *///from w ww. ja va 2 s . c o m public Document render(RequestContext context) throws Exception { // check if we need to produce a new chart if (dirty) { // clear old listeners dispatcher.clear(); this.result = olapModel.getResult(); this.cellIterator = result.getCells().iterator(); this.dimCount = result.getAxes().length; DefaultCategoryDataset dataset = null; switch (dimCount) { case 1: logger.info("1-dim data"); dataset = build1dimDataset(); break; case 2: logger.info("2-dim data"); dataset = build2dimDataset(); break; default: logger.error("less than 1 or more than 2 dimensions"); throw new IllegalArgumentException("ChartRenderer requires a 1 or 2 dimensional result"); } // re-set dirty flag dirty = false; // create font titleFont = new java.awt.Font(fontName, fontStyle, fontSize); CategoryURLGenerator urlGenerator = new jpivotCategoryURLGenerator(webControllerURL); // Create the chart object JFreeChart chart = null; switch (chartType) { case 1: chart = ChartFactory.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 2: chart = ChartFactory.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 3: chart = ChartFactory.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 4: chart = ChartFactory.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 5: chart = ChartFactory.createStackedBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 6: chart = ChartFactory.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 7: chart = ChartFactory.createStackedBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 8: chart = ChartFactory.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 9: chart = ChartFactory.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 10: chart = ChartFactory.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 11: chart = ChartFactory.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 12: chart = ChartFactory.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 13: chart = ChartFactory.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 14: chart = ChartFactory.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator); break; case 15: chart = ChartFactory.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN, showLegend, showTooltips, drillThroughEnabled, new jpivotPieURLGenerator(TableOrder.BY_COLUMN, dataset, webControllerURL)); break; case 16: chart = ChartFactory.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW, showLegend, showTooltips, drillThroughEnabled, new jpivotPieURLGenerator(TableOrder.BY_ROW, dataset, webControllerURL)); break; case 17: chart = ChartFactory.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN, showLegend, showTooltips, drillThroughEnabled, new jpivotPieURLGenerator(TableOrder.BY_COLUMN, dataset, webControllerURL)); break; case 18: chart = ChartFactory.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW, showLegend, showTooltips, drillThroughEnabled, new jpivotPieURLGenerator(TableOrder.BY_ROW, dataset, webControllerURL)); break; default: throw new Exception("An unknown Chart Type was requested"); } try { chart.setBackgroundPaint(new java.awt.Color(bgColorR, bgColorG, bgColorB)); java.awt.Font slicerFont = new java.awt.Font(slicerFontName, slicerFontStyle, slicerFontSize); java.awt.Font axisFont = new java.awt.Font(axisFontName, axisFontStyle, axisFontSize); java.awt.Font axisTickFont = new java.awt.Font(axisTickFontName, axisTickFontStyle, axisTickFontSize); java.awt.Font legendFont = new java.awt.Font(legendFontName, legendFontStyle, legendFontSize); Plot plot = chart.getPlot(); if (plot instanceof CategoryPlot) { CategoryPlot catPlot = (CategoryPlot) plot; catPlot.getDomainAxis().setLabelFont(axisFont); catPlot.getRangeAxis().setLabelFont(axisFont); catPlot.getDomainAxis().setTickLabelFont(axisTickFont); catPlot.getRangeAxis().setTickLabelFont(axisTickFont); catPlot.getDomainAxis().setMaximumCategoryLabelWidthRatio(100.0f); double angle = -2.0 * Math.PI / 360.0 * (double) tickLabelRotate; CategoryLabelPositions oldp = catPlot.getDomainAxis().getCategoryLabelPositions(); CategoryLabelPositions newp = new CategoryLabelPositions( oldp.getLabelPosition(RectangleEdge.TOP), new CategoryLabelPosition(RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, angle, CategoryLabelWidthType.RANGE, 0.0f), oldp.getLabelPosition(RectangleEdge.LEFT), oldp.getLabelPosition(RectangleEdge.RIGHT)); catPlot.getDomainAxis().setCategoryLabelPositions(newp); } else if (plot instanceof PiePlot3D) { PiePlot3D piePlot = (PiePlot3D) plot; //piePlot.setSectionLabelFont(axisFont); piePlot.setLabelFont(axisFont); //piePlot.setSeriesLabelFont(axisTickFont); //piePlot.setSectionLabelType(piePlot.NO_LABELS); piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE); piePlot.setForegroundAlpha(0.5f); piePlot.setNoDataMessage("No data to display"); } else if (plot instanceof PiePlot) { PiePlot piePlot = (PiePlot) plot; //piePlot.setSectionLabelFont(axisFont); //piePlot.setSeriesLabelFont(axisTickFont); piePlot.setLabelFont(axisFont); //piePlot.setSectionLabelType(piePlot.NO_LABELS); } LegendTitle legend = (LegendTitle) chart.getLegend(); if (legend != null) { legend.setItemFont(legendFont); /* RectangleAnchor legendRectAnchor=RectangleAnchor.BOTTOM; switch (legendPosition){ case 0: legendRectAnchor = RectangleAnchor.LEFT; break; case 1: legendRectAnchor = RectangleAnchor.TOP; break; case 2: legendRectAnchor = RectangleAnchor.RIGHT; break; case 3: legendRectAnchor = RectangleAnchor.BOTTOM; break; } legend.setLegendItemGraphicAnchor(legendRectAnchor); */ RectangleEdge legendRectEdge = RectangleEdge.BOTTOM; switch (legendPosition) { case 0: legendRectEdge = RectangleEdge.LEFT; break; case 1: legendRectEdge = RectangleEdge.TOP; break; case 2: legendRectEdge = RectangleEdge.RIGHT; break; case 3: legendRectEdge = RectangleEdge.BOTTOM; break; } legend.setPosition(legendRectEdge); } if (showSlicer) { RectangleEdge slicerRectPos = RectangleEdge.BOTTOM; HorizontalAlignment slicerHorizAlignment = HorizontalAlignment.LEFT; switch (slicerPosition) { case 0: slicerRectPos = RectangleEdge.TOP; break; case 1: slicerRectPos = RectangleEdge.BOTTOM; break; case 2: slicerRectPos = RectangleEdge.RIGHT; break; case 3: slicerRectPos = RectangleEdge.LEFT; break; } switch (slicerAlignment) { case 4: slicerHorizAlignment = HorizontalAlignment.CENTER; break; case 3: slicerHorizAlignment = HorizontalAlignment.LEFT; break; case 2: slicerHorizAlignment = HorizontalAlignment.RIGHT; break; } TextTitle slicer = new TextTitle(buildSlicer(), slicerFont, Color.BLACK, slicerRectPos, slicerHorizAlignment, VerticalAlignment.CENTER, new RectangleInsets(0, 0, 0, 0)); slicer.setPosition(slicerRectPos); chart.addSubtitle(slicer); } info = new ChartRenderingInfo(new StandardEntityCollection()); // Write the chart image to the temporary directory HttpSession session = context.getSession(); filename = ServletUtilities.saveChartAsPNG(chart, chartWidth, chartHeight, info, session); } catch (Exception e) { filename = "public_error_500x300.png"; dirty = true; } } // new DOM document DocumentBuilder parser = XmlUtils.getParser(); // get an image map for the chart, wrap it in xchart tags String xchart = "<xchart>" + writeImageMap(filename, info, false) + "</xchart>"; /* if (logger.isDebugEnabled()) { logger.debug("Chart XML"); logger.debug(xchart); } */ // create an InputStream from the DOM document InputStream stream = new ByteArrayInputStream(xchart.getBytes("UTF-8")); document = parser.parse(stream); Element root = document.getDocumentElement(); // create url for img tag String graphURL = getGraphURL(context); Element img = document.createElement("img"); img.setAttribute("src", graphURL); img.setAttribute("width", new Integer(chartWidth).toString()); img.setAttribute("height", new Integer(chartHeight).toString()); img.setAttribute("style", "border:0;"); img.setAttribute("usemap", "#" + filename); root.appendChild(img); return document; }
From source file:com.modeln.build.ctrl.charts.CMnBuildListChart.java
/** * Return rendering information for the chart. *///w ww .j a v a 2s . c o m public static final ChartRenderingInfo getAreaTestTimeRenderingInfo() { return new ChartRenderingInfo(new StandardEntityCollection()); }
From source file:org.pentaho.platform.plugin.action.jfreechart.ChartComponent.java
@Override protected boolean executeAction() { int height = -1; int width = -1; String title = ""; //$NON-NLS-1$ Node chartDocument = null;//from w w w. j a va2 s.c o m IPentahoResultSet data = (IPentahoResultSet) getInputValue(ChartComponent.CHART_DATA_PROP); if (!data.isScrollable()) { getLogger().debug("ResultSet is not scrollable. Copying into memory"); //$NON-NLS-1$ IPentahoResultSet memSet = data.memoryCopy(); data.close(); data = memSet; } String urlTemplate = (String) getInputValue(ChartComponent.URL_TEMPLATE); Node chartAttributes = null; String chartAttributeString = null; // Attempt to get chart attributes as an input string or as a resource file // If these don't trip, then we assume the chart attributes are defined in // the component-definition of the chart action. if (getInputNames().contains(ChartComponent.CHART_ATTRIBUTES_PROP)) { chartAttributeString = getInputStringValue(ChartComponent.CHART_ATTRIBUTES_PROP); } else if (isDefinedResource(ChartComponent.CHART_ATTRIBUTES_PROP)) { IActionSequenceResource resource = getResource(ChartComponent.CHART_ATTRIBUTES_PROP); chartAttributeString = getResourceAsString(resource); } // Realize chart attributes as an XML document if (chartAttributeString != null) { try { chartDocument = XmlDom4JHelper.getDocFromString(chartAttributeString, new PentahoEntityResolver()); } catch (XmlParseException e) { getLogger().error( Messages.getInstance().getString("ChartComponent.ERROR_0005_CANT_DOCUMENT_FROM_STRING"), e); //$NON-NLS-1$ return false; } chartAttributes = chartDocument.selectSingleNode(ChartComponent.CHART_ATTRIBUTES_PROP); // This line of code handles a discrepancy between the schema of a chart definition // handed to a dashboard versus a ChartComponent schema. The top level node for the dashboard charts // is <chart>, whereas the ChartComponent expects <chart-attributes>. // TODO: // This discrepancy should be resolved when we have ONE chart solution. if (chartAttributes == null) { chartAttributes = chartDocument.selectSingleNode(ChartComponent.ALTERNATIVE_CHART_ATTRIBUTES_PROP); } } // Default chart attributes are in the component-definition section of the action definition. if (chartAttributes == null) { chartAttributes = getComponentDefinition(true).selectSingleNode(ChartComponent.CHART_ATTRIBUTES_PROP); } // URL click-through attributes (useBaseURL, target) are only processed IF we // have an urlTemplate attribute if ((urlTemplate == null) || (urlTemplate.length() == 0)) { if (chartAttributes.selectSingleNode(ChartComponent.URL_TEMPLATE) != null) { urlTemplate = chartAttributes.selectSingleNode(ChartComponent.URL_TEMPLATE).getText(); } } // These parameters are replacement variables parsed into the // urlTemplate specifically when we have a URL that is a drill-through // link in a chart intended to drill down into the chart data. String parameterName = (String) getInputValue(ChartComponent.PARAMETER_NAME); if ((parameterName == null) || (parameterName.length() == 0)) { if (chartAttributes.selectSingleNode(ChartComponent.PARAMETER_NAME) != null) { parameterName = chartAttributes.selectSingleNode(ChartComponent.PARAMETER_NAME).getText(); } } // These parameters are replacement variables parsed into the // urlTemplate specifically when we have a URL that is a drill-through // link in a chart intended to drill down into the chart data. String outerParameterName = (String) getInputValue(ChartComponent.OUTER_PARAMETER_NAME); if ((outerParameterName == null) || (outerParameterName.length() == 0)) { if (chartAttributes.selectSingleNode(ChartComponent.OUTER_PARAMETER_NAME) != null) { outerParameterName = chartAttributes.selectSingleNode(ChartComponent.OUTER_PARAMETER_NAME) .getText(); } } String chartType = chartAttributes.selectSingleNode(ChartDefinition.TYPE_NODE_NAME).getText(); // --------------- This code allows inputs to override the chartAttributes // of width, height, and title Object widthObj = getInputValue(ChartDefinition.WIDTH_NODE_NAME); if (widthObj != null) { width = Integer.parseInt(widthObj.toString()); if (width != -1) { if (chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME) == null) { ((Element) chartAttributes).addElement(ChartDefinition.WIDTH_NODE_NAME); } chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME).setText(Integer.toString(width)); } } Object heightObj = getInputValue(ChartDefinition.HEIGHT_NODE_NAME); if (heightObj != null) { height = Integer.parseInt(heightObj.toString()); if (height != -1) { if (chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME) == null) { ((Element) chartAttributes).addElement(ChartDefinition.HEIGHT_NODE_NAME); } chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME) .setText(Integer.toString(height)); } } Object titleObj = getInputValue(ChartDefinition.TITLE_NODE_NAME); if (titleObj != null) { if (chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME) == null) { ((Element) chartAttributes).addElement(ChartDefinition.TITLE_NODE_NAME); } chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME).setText(titleObj.toString()); } // ----------------End of Override // ---------------Feed the Title and Subtitle information through the input substitution Node titleNode = chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME); if (titleNode != null) { String titleStr = titleNode.getText(); if (titleStr != null) { title = titleStr; String newTitle = applyInputsToFormat(titleStr); titleNode.setText(newTitle); } } List subtitles = chartAttributes.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME); if ((subtitles == null) || (subtitles.isEmpty())) { Node subTitlesNode = chartAttributes.selectSingleNode(ChartDefinition.SUBTITLES_NODE_NAME); if (subTitlesNode != null) { subtitles = chartAttributes.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME); } } else { // log a deprecation warning for this property... getLogger().warn(Messages.getInstance().getString("CHART.WARN_DEPRECATED_CHILD", //$NON-NLS-1$ ChartDefinition.SUBTITLE_NODE_NAME, ChartDefinition.SUBTITLES_NODE_NAME)); getLogger().warn(Messages.getInstance().getString("CHART.WARN_PROPERTY_WILL_NOT_VALIDATE", //$NON-NLS-1$ ChartDefinition.SUBTITLE_NODE_NAME)); } if (subtitles != null) { for (Iterator iter = subtitles.iterator(); iter.hasNext();) { Node subtitleNode = (Node) iter.next(); if (subtitleNode != null) { String subtitleStr = subtitleNode.getText(); if (subtitleStr != null) { String newSubtitle = applyInputsToFormat(subtitleStr); subtitleNode.setText(newSubtitle); } } } } // ----------------End of Format // Determine if we are going to read the chart data set by row or by column boolean byRow = false; if (getInputStringValue(ChartComponent.BY_ROW_PROP) != null) { byRow = Boolean.valueOf(getInputStringValue(ChartComponent.BY_ROW_PROP)).booleanValue(); } // TODO Figure out why these overrides are called here. Seems like we are doing the same thing we just did above, // but // could possibly step on the height and width values set previously. if (height == -1) { height = (int) getInputLongValue( ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.HEIGHT_NODE_NAME, 50); //$NON-NLS-1$ } if (width == -1) { width = (int) getInputLongValue( ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.WIDTH_NODE_NAME, 100); //$NON-NLS-1$ } if (title.length() <= 0) { title = getInputStringValue( ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.TITLE_NODE_NAME); //$NON-NLS-1$ } // Select the right dataset to use based on the chart type // Default to category dataset String datasetType = ChartDefinition.CATEGORY_DATASET_STR; boolean isStacked = false; Node datasetTypeNode = chartAttributes.selectSingleNode(ChartDefinition.DATASET_TYPE_NODE_NAME); if (datasetTypeNode != null) { datasetType = datasetTypeNode.getText(); } Dataset dataDefinition = null; if (ChartDefinition.XY_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) { dataDefinition = new XYSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession()); } else if (ChartDefinition.TIME_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) { Node stackedNode = chartAttributes.selectSingleNode(ChartDefinition.STACKED_NODE_NAME); if (stackedNode != null) { isStacked = Boolean.valueOf(stackedNode.getText()).booleanValue(); } if ((isStacked) && (ChartDefinition.AREA_CHART_STR.equalsIgnoreCase(chartType))) { dataDefinition = new TimeTableXYDatasetChartDefinition(data, byRow, chartAttributes, getSession()); } else { dataDefinition = new TimeSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession()); } } else if (ChartDefinition.PIE_CHART_STR.equalsIgnoreCase(chartType)) { dataDefinition = new PieDatasetChartDefinition(data, byRow, chartAttributes, getSession()); } else if (ChartDefinition.DIAL_CHART_STR.equalsIgnoreCase(chartType)) { dataDefinition = new DialWidgetDefinition(data, byRow, chartAttributes, width, height, getSession()); } else if (ChartDefinition.BAR_LINE_CHART_STR.equalsIgnoreCase(chartType)) { dataDefinition = new BarLineChartDefinition(data, byRow, chartAttributes, getSession()); } else if (ChartDefinition.BUBBLE_CHART_STR.equalsIgnoreCase(chartType)) { dataDefinition = new XYZSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession()); } else { dataDefinition = new CategoryDatasetChartDefinition(data, byRow, chartAttributes, getSession()); } // Determine what we are sending back - Default to OUTPUT_PNG output // OUTPUT_PNG = the chart gets written to a file in .png format // OUTPUT_SVG = the chart gets written to a file in .svg (XML) format // OUTPUT_CHART = the chart in a byte stream gets stored as as an IContentItem // OUTPUT_PNG_BYTES = the chart gets sent as a byte stream in .png format int outputType = JFreeChartEngine.OUTPUT_PNG; if (getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP) != null) { if (ChartComponent.SVG_TYPE.equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) { outputType = JFreeChartEngine.OUTPUT_SVG; } else if (ChartComponent.CHART_TYPE .equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) { outputType = JFreeChartEngine.OUTPUT_CHART; } else if (ChartComponent.PNG_BYTES_TYPE .equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) { outputType = JFreeChartEngine.OUTPUT_PNG_BYTES; } } boolean keepTempFile = false; if (isDefinedInput(KEEP_TEMP_FILE_PROP)) { keepTempFile = getInputBooleanValue(KEEP_TEMP_FILE_PROP, false); } JFreeChart chart = null; switch (outputType) { /**************************** OUTPUT_PNG_BYTES *********************************************/ case JFreeChartEngine.OUTPUT_PNG_BYTES: chart = JFreeChartEngine.getChart(dataDefinition, title, "", width, height, this); //$NON-NLS-1$ // TODO Shouldn't the mime types and other strings here be constant somewhere? Where do we // put this type of general info ? String mimeType = "image/png"; //$NON-NLS-1$ IContentItem contentItem = getOutputItem("chartdata", mimeType, ".png"); //$NON-NLS-1$ //$NON-NLS-2$ contentItem.setMimeType(mimeType); try { OutputStream output = contentItem.getOutputStream(getActionName()); ChartUtilities.writeChartAsPNG(output, chart, width, height); } catch (Exception e) { error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0004_CANT_CREATE_IMAGE"), e); //$NON-NLS-1$ return false; } break; /**************************** OUTPUT_SVG && OUTPUT_PNG *************************************/ case JFreeChartEngine.OUTPUT_SVG: // intentionally fall through to PNG case JFreeChartEngine.OUTPUT_PNG: // Don't include the map in a file if HTML_MAPPING_HTML is specified, as that // param sends the map back on the outputstream as a string boolean createMapFile = !isDefinedOutput(ChartComponent.HTML_MAPPING_HTML); boolean hasTemplate = urlTemplate != null && urlTemplate.length() > 0; File[] fileResults = createTempFile(outputType, hasTemplate, !keepTempFile); if (fileResults == null) { error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0003_CANT_CREATE_TEMP_FILES")); //$NON-NLS-1$ return false; } String chartId = fileResults[ChartComponent.FILE_NAME].getName().substring(0, fileResults[ChartComponent.FILE_NAME].getName().indexOf('.')); String filePathWithoutExtension = ChartComponent.TEMP_DIRECTORY + chartId; PrintWriter printWriter = new PrintWriter(new StringWriter()); ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); JFreeChartEngine.saveChart(dataDefinition, title, "", filePathWithoutExtension, width, height, //$NON-NLS-1$ outputType, printWriter, info, this); // Creating the image map boolean useBaseUrl = true; String urlTarget = "pentaho_popup"; //$NON-NLS-1$ // Prepend the base url to the front of every drill through link if (chartAttributes.selectSingleNode(ChartComponent.USE_BASE_URL_TAG) != null) { Boolean booleanValue = new Boolean( chartAttributes.selectSingleNode(ChartComponent.USE_BASE_URL_TAG).getText()); useBaseUrl = booleanValue.booleanValue(); } // What target for link? _parent, _blank, etc. if (chartAttributes.selectSingleNode(ChartComponent.URL_TARGET_TAG) != null) { urlTarget = chartAttributes.selectSingleNode(ChartComponent.URL_TARGET_TAG).getText(); } String mapString = null; if (hasTemplate) { try { String mapId = fileResults[ChartComponent.MAP_NAME].getName().substring(0, fileResults[ChartComponent.MAP_NAME].getName().indexOf('.')); mapString = ImageMapUtilities.getImageMap(mapId, info, new StandardToolTipTagFragmentGenerator(), new PentahoChartURLTagFragmentGenerator(urlTemplate, urlTarget, useBaseUrl, dataDefinition, parameterName, outerParameterName)); if (createMapFile) { BufferedWriter out = new BufferedWriter( new FileWriter(fileResults[ChartComponent.MAP_NAME])); out.write(mapString); out.flush(); out.close(); } } catch (IOException e) { error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0001_CANT_WRITE_MAP", //$NON-NLS-1$ fileResults[ChartComponent.MAP_NAME].getPath())); return false; } catch (Exception e) { error(e.getLocalizedMessage(), e); return false; } } /******************************************************************************************************* * Legitimate outputs for the ChartComponent in an action sequence: * * CHART_OUTPUT (chart-output) Stores the chart in the content repository as an IContentItem. * * CHART_FILE_NAME_OUTPUT (chart-filename) Returns the name of the chart file, including the file extension * (with no path information) as a String. * * HTML_MAPPING_OUTPUT (chart-mapping) Returns the name of the file that the map has been saved to, including * the file extension (with no path information) as a String. Will be empty if url-template is undefined * * HTML_MAPPING_HTML (chart-map-html) Returns the chart image map HTML as a String. Will be empty if * url-template is undefined * * BASE_URL_OUTPUT (base-url) Returns the web app's base URL (ie., http://localhost:8080/pentaho) as a String. * * HTML_IMG_TAG (image-tag) Returns the HTML snippet including the image map, image (<IMG />) tag for the chart * image with src, width, height and usemap attributes defined. Usemap will not be included if url-template is * undefined. * *******************************************************************************************************/ // Now set the outputs Set outputs = getOutputNames(); if ((outputs != null) && (outputs.size() > 0)) { Iterator iter = outputs.iterator(); while (iter.hasNext()) { String outputName = (String) iter.next(); String outputValue = null; if (outputName.equals(ChartComponent.CHART_FILE_NAME_OUTPUT)) { outputValue = fileResults[ChartComponent.FILE_NAME].getName(); } else if (outputName.equals(ChartComponent.HTML_MAPPING_OUTPUT)) { if (hasTemplate) { outputValue = fileResults[ChartComponent.MAP_NAME].getName(); } } else if (outputName.equals(ChartComponent.HTML_MAPPING_HTML)) { outputValue = mapString; } else if (outputName.equals(ChartComponent.BASE_URL_OUTPUT)) { IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext(); outputValue = requestContext.getContextPath(); } else if (outputName.equals(ChartComponent.CONTEXT_PATH_OUTPUT)) { IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext(); outputValue = requestContext.getContextPath(); } else if (outputName.equals(ChartComponent.FULLY_QUALIFIED_SERVER_URL_OUTPUT)) { IApplicationContext applicationContext = PentahoSystem.getApplicationContext(); if (applicationContext != null) { outputValue = applicationContext.getFullyQualifiedServerURL(); } else { IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext(); outputValue = requestContext.getContextPath(); } } else if (outputName.equals(ChartComponent.HTML_IMG_TAG)) { outputValue = hasTemplate ? mapString : ""; //$NON-NLS-1$ outputValue += "<img border=\"0\" "; //$NON-NLS-1$ outputValue += "width=\"" + width + "\" "; //$NON-NLS-1$//$NON-NLS-2$ outputValue += "height=\"" + height + "\" "; //$NON-NLS-1$//$NON-NLS-2$ if (hasTemplate) { outputValue += "usemap=\"#" + fileResults[ChartComponent.MAP_NAME].getName().substring( 0, fileResults[ChartComponent.MAP_NAME].getName().indexOf('.')) + "\" "; //$NON-NLS-1$//$NON-NLS-2$ } IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext(); String contextPath = requestContext.getContextPath(); outputValue += "src=\"" + contextPath + "getImage?image=" //$NON-NLS-1$//$NON-NLS-2$ + fileResults[ChartComponent.FILE_NAME].getName() + "\"/>"; //$NON-NLS-1$ } if (outputValue != null) { setOutputValue(outputName, outputValue); } } } break; /************************** OUTPUT_CHART && DEFAULT *************************************/ case JFreeChartEngine.OUTPUT_CHART: // intentionally fall through to default default: String chartName = ChartComponent.CHART_OUTPUT; if (isDefinedInput(ChartComponent.CHART_NAME_PROP)) { chartName = getInputStringValue(ChartComponent.CHART_NAME_PROP); } chart = JFreeChartEngine.getChart(dataDefinition, title, "", width, height, this); //$NON-NLS-1$ setOutputValue(chartName, chart); break; } return true; }
From source file:gov.nih.nci.rembrandt.web.graphing.data.GeneExpressionPlot.java
public static HashMap generateBarChart(String gene, String reporter, HttpSession session, PrintWriter pw, GeneExpressionDataSetType geType) { String log2Filename = null;/*from w w w. j a v a 2 s . c o m*/ String rawFilename = null; String medianFilename = null; String bwFilename = ""; String legendHtml = null; HashMap charts = new HashMap(); PlotSize ps = PlotSize.MEDIUM; final String geneName = gene; final String alg = geType.equals(GeneExpressionDataSetType.GeneExpressionDataSet) ? RembrandtConstants.REPORTER_SELECTION_AFFY : RembrandtConstants.REPORTER_SELECTION_UNI; try { InstitutionCriteria institutionCriteria = InsitutionAccessHelper.getInsititutionCriteria(session); final GenePlotDataSet gpds = new GenePlotDataSet(gene, reporter, institutionCriteria, geType, session.getId()); //final GenePlotDataSet gpds = new GenePlotDataSet(gene, institutionCriteria,GeneExpressionDataSetType.GeneExpressionDataSet ); //LOG2 Dataset DefaultStatisticalCategoryDataset dataset = (DefaultStatisticalCategoryDataset) gpds.getLog2Dataset(); //RAW Dataset CategoryDataset meanDataset = (CategoryDataset) gpds.getRawDataset(); //B&W dataset DefaultBoxAndWhiskerCategoryDataset bwdataset = (DefaultBoxAndWhiskerCategoryDataset) gpds .getBwdataset(); //Median dataset CategoryDataset medianDataset = (CategoryDataset) gpds.getMedianDataset(); charts.put("diseaseSampleCountMap", gpds.getDiseaseSampleCountMap()); //IMAGE Size Control if (bwdataset != null && bwdataset.getRowCount() > 5) { ps = PlotSize.LARGE; } else { ps = PlotSize.MEDIUM; } //SMALL/MEDIUM == 650 x 400 //LARGE == 1000 x 400 //put as external Props? int imgW = 650; if (ps == PlotSize.LARGE) { imgW = new BigDecimal(bwdataset.getRowCount()).multiply(new BigDecimal(75)).intValue() > 1000 ? new BigDecimal(bwdataset.getRowCount()).multiply(new BigDecimal(75)).intValue() : 1000; } JFreeChart bwChart = null; //B&W plot CategoryAxis xAxis = new CategoryAxis("Disease Type"); NumberAxis yAxis = new NumberAxis("Log2 Expression Intensity"); yAxis.setAutoRangeIncludesZero(true); BoxAndWhiskerCoinPlotRenderer bwRenderer = null; // BoxAndWhiskerRenderer bwRenderer = new BoxAndWhiskerRenderer(); if (reporter != null) { //single reporter, show the coins bwRenderer = new BoxAndWhiskerCoinPlotRenderer(gpds.getCoinHash()); bwRenderer.setDisplayCoinCloud(true); bwRenderer.setDisplayMean(false); bwRenderer.setDisplayAllOutliers(true); bwRenderer.setToolTipGenerator(new CategoryToolTipGenerator() { public String generateToolTip(CategoryDataset dataset, int series, int item) { String tt = ""; NumberFormat formatter = new DecimalFormat(".####"); String key = ""; //String s = formatter.format(-1234.567); // -001235 if (dataset instanceof DefaultBoxAndWhiskerCategoryDataset) { DefaultBoxAndWhiskerCategoryDataset ds = (DefaultBoxAndWhiskerCategoryDataset) dataset; try { String med = formatter.format(ds.getMedianValue(series, item)); tt += "Median: " + med + "<br/>"; tt += "Mean: " + formatter.format(ds.getMeanValue(series, item)) + "<br/>"; tt += "Q1: " + formatter.format(ds.getQ1Value(series, item)) + "<br/>"; tt += "Q3: " + formatter.format(ds.getQ3Value(series, item)) + "<br/>"; tt += "Max: " + formatter.format( FaroutOutlierBoxAndWhiskerCalculator.getMaxFaroutOutlier(ds, series, item)) + "<br/>"; tt += "Min: " + formatter.format( FaroutOutlierBoxAndWhiskerCalculator.getMinFaroutOutlier(ds, series, item)) + "<br/>"; //tt += "<br/><br/>Please click on the box and whisker to view a plot for this reporter.<br/>"; //tt += "X: " + ds.getValue(series, item).toString()+"<br/>"; //tt += "<br/><a href=\\\'#\\\' id=\\\'"+ds.getRowKeys().get(series)+"\\\' onclick=\\\'alert(this.id);return false;\\\'>"+ds.getRowKeys().get(series)+" plot</a><br/><br/>"; key = ds.getRowKeys().get(series).toString(); } catch (Exception e) { } } return tt; } }); } else { //groups, dont show coins bwRenderer = new BoxAndWhiskerCoinPlotRenderer(); bwRenderer.setDisplayAllOutliers(true); bwRenderer.setToolTipGenerator(new CategoryToolTipGenerator() { public String generateToolTip(CategoryDataset dataset, int series, int item) { String tt = ""; NumberFormat formatter = new DecimalFormat(".####"); String key = ""; //String s = formatter.format(-1234.567); // -001235 if (dataset instanceof DefaultBoxAndWhiskerCategoryDataset) { DefaultBoxAndWhiskerCategoryDataset ds = (DefaultBoxAndWhiskerCategoryDataset) dataset; try { String med = formatter.format(ds.getMedianValue(series, item)); tt += "Median: " + med + "<br/>"; tt += "Mean: " + formatter.format(ds.getMeanValue(series, item)) + "<br/>"; tt += "Q1: " + formatter.format(ds.getQ1Value(series, item)) + "<br/>"; tt += "Q3: " + formatter.format(ds.getQ3Value(series, item)) + "<br/>"; tt += "Max: " + formatter.format( FaroutOutlierBoxAndWhiskerCalculator.getMaxFaroutOutlier(ds, series, item)) + "<br/>"; tt += "Min: " + formatter.format( FaroutOutlierBoxAndWhiskerCalculator.getMinFaroutOutlier(ds, series, item)) + "<br/>"; tt += "<br/><br/>Please click on the box and whisker to view a plot for this reporter.<br/>"; //tt += "X: " + ds.getValue(series, item).toString()+"<br/>"; //tt += "<br/><a href=\\\'#\\\' id=\\\'"+ds.getRowKeys().get(series)+"\\\' onclick=\\\'alert(this.id);return false;\\\'>"+ds.getRowKeys().get(series)+" plot</a><br/><br/>"; key = ds.getRowKeys().get(series).toString(); } catch (Exception e) { } } return "onclick=\"popCoin('" + geneName + "','" + key + "', '" + alg + "');\" | " + tt; } }); } bwRenderer.setFillBox(false); CategoryPlot bwPlot = new CategoryPlot(bwdataset, xAxis, yAxis, bwRenderer); bwChart = new JFreeChart(bwPlot); // JFreeChart bwChart = new JFreeChart( // null /*"Gene Expression Plot (" + gene.toUpperCase() + ")"*/, // new Font("SansSerif", Font.BOLD, 14), // bwPlot, // true // ); bwChart.setBackgroundPaint(java.awt.Color.white); //bwChart.getTitle().setHorizontalAlignment(TextTitle.DEFAULT_HORIZONTAL_ALIGNMENT.LEFT); bwChart.removeLegend(); //END BW plot // create the chart...for LOG2 dataset JFreeChart log2Chart = ChartFactory.createBarChart( null /*"Gene Expression Plot (" + gene.toUpperCase() + ")"*/, // chart // title "Groups", // domain axis label "Log2 Expression Intensity", // range axis label dataset, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips? false // URLs? ); //create the chart .... for RAW dataset JFreeChart meanChart = ChartFactory.createBarChart( null /*"Gene Expression Plot (" + gene.toUpperCase() + ")"*/, // chart // title "Groups", // domain axis label "Mean Expression Intensity", // range axis label meanDataset, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips? false // URLs? ); // create the chart .... for Median dataset JFreeChart medianChart = ChartFactory.createBarChart( null /*"Gene Expression Plot (" + gene.toUpperCase() + ")"*/, // chart // title "Groups", // domain axis label "Median Expression Intensity", // range axis label medianDataset, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips? false // URLs? ); log2Chart.setBackgroundPaint(java.awt.Color.white); // lets start some customization to retro fit w/jcharts lookand feel CategoryPlot log2Plot = log2Chart.getCategoryPlot(); CategoryAxis log2Axis = log2Plot.getDomainAxis(); log2Axis.setLowerMargin(0.02); // two percent log2Axis.setCategoryMargin(0.20); // 20 percent log2Axis.setUpperMargin(0.02); // two percent // same for our fake chart - just to get the tooltips meanChart.setBackgroundPaint(java.awt.Color.white); CategoryPlot meanPlot = meanChart.getCategoryPlot(); CategoryAxis meanAxis = meanPlot.getDomainAxis(); meanAxis.setLowerMargin(0.02); // two percent meanAxis.setCategoryMargin(0.20); // 20 percent meanAxis.setUpperMargin(0.02); // two percent // median plot medianChart.setBackgroundPaint(java.awt.Color.white); CategoryPlot medianPlot = medianChart.getCategoryPlot(); CategoryAxis medianAxis = medianPlot.getDomainAxis(); medianAxis.setLowerMargin(0.02); // two percent medianAxis.setCategoryMargin(0.20); // 20 percent medianAxis.setUpperMargin(0.02); // two percent // customise the renderer... StatisticalBarRenderer log2Renderer = new StatisticalBarRenderer(); // BarRenderer renderer = (BarRenderer) plot.getRenderer(); log2Renderer.setItemMargin(0.01); // one percent log2Renderer.setDrawBarOutline(true); log2Renderer.setOutlinePaint(Color.BLACK); log2Renderer.setToolTipGenerator(new CategoryToolTipGenerator() { public String generateToolTip(CategoryDataset dataset, int series, int item) { HashMap pv = gpds.getPValuesHashMap(); HashMap std_d = gpds.getStdDevMap(); String currentPV = (String) pv .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item)); String stdDev = (String) std_d .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item)); return "Probeset : " + dataset.getRowKey(series) + "<br/>Intensity : " + new DecimalFormat("0.0000").format(dataset.getValue(series, item)) + "<br/>" + RembrandtConstants.PVALUE + " : " + currentPV + "<br/>Std. Dev.: " + stdDev + "<br/>"; } }); log2Plot.setRenderer(log2Renderer); // customize the renderer BarRenderer meanRenderer = (BarRenderer) meanPlot.getRenderer(); meanRenderer.setItemMargin(0.01); // one percent meanRenderer.setDrawBarOutline(true); meanRenderer.setOutlinePaint(Color.BLACK); meanRenderer.setToolTipGenerator(new CategoryToolTipGenerator() { public String generateToolTip(CategoryDataset dataset, int series, int item) { HashMap pv = gpds.getPValuesHashMap(); HashMap std_d = gpds.getStdDevMap(); String currentPV = (String) pv .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item)); String stdDev = (String) std_d .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item)); return "Probeset : " + dataset.getRowKey(series) + "<br/>Intensity : " + new DecimalFormat("0.0000").format(dataset.getValue(series, item)) + "<br/>" + RembrandtConstants.PVALUE + ": " + currentPV + "<br/>"; //"<br/>Std. Dev.: " + stdDev + "<br/>"; } }); meanPlot.setRenderer(meanRenderer); // customize the renderer BarRenderer medianRenderer = (BarRenderer) medianPlot.getRenderer(); medianRenderer.setItemMargin(0.01); // one percent medianRenderer.setDrawBarOutline(true); medianRenderer.setOutlinePaint(Color.BLACK); medianRenderer.setToolTipGenerator(new CategoryToolTipGenerator() { public String generateToolTip(CategoryDataset dataset, int series, int item) { HashMap pv = gpds.getPValuesHashMap(); HashMap std_d = gpds.getStdDevMap(); String currentPV = (String) pv .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item)); String stdDev = (String) std_d .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item)); return "Probeset : " + dataset.getRowKey(series) + "<br/>Intensity : " + new DecimalFormat("0.0000").format(dataset.getValue(series, item)) + "<br/>" + RembrandtConstants.PVALUE + ": " + currentPV + "<br/>"; //"<br/>Std. Dev.: " + stdDev + "<br/>"; } }); // LegendTitle lg = chart.getLegend(); medianPlot.setRenderer(medianRenderer); // lets generate a custom legend - assumes theres only one source? LegendItemCollection lic = log2Chart.getLegend().getSources()[0].getLegendItems(); legendHtml = LegendCreator.buildLegend(lic, "Probesets"); log2Chart.removeLegend(); meanChart.removeLegend(); medianChart.removeLegend(); //bwChart.removeLegend(); // <-- do this above // Write the chart image to the temporary directory ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); // BW if (bwChart != null) { int bwwidth = new BigDecimal(1.5).multiply(new BigDecimal(imgW)).intValue(); bwFilename = ServletUtilities.saveChartAsPNG(bwChart, bwwidth, 400, info, session); CustomOverlibToolTipTagFragmentGenerator ttip = new CustomOverlibToolTipTagFragmentGenerator(); String toolTip = " href='javascript:void(0);' alt='GeneChart JFreechart Plot' "; ttip.setExtra(toolTip); //must have href for area tags to have cursor:pointer ChartUtilities.writeImageMap(pw, bwFilename, info, ttip, new StandardURLTagFragmentGenerator()); info.clear(); // lose the first one info = new ChartRenderingInfo(new StandardEntityCollection()); } //END BW log2Filename = ServletUtilities.saveChartAsPNG(log2Chart, imgW, 400, info, session); CustomOverlibToolTipTagFragmentGenerator ttip = new CustomOverlibToolTipTagFragmentGenerator(); String toolTip = " alt='GeneChart JFreechart Plot' "; ttip.setExtra(toolTip); //must have href for area tags to have cursor:pointer ChartUtilities.writeImageMap(pw, log2Filename, info, ttip, new StandardURLTagFragmentGenerator()); // clear the first one and overwrite info with our second one - no // error bars info.clear(); // lose the first one info = new ChartRenderingInfo(new StandardEntityCollection()); rawFilename = ServletUtilities.saveChartAsPNG(meanChart, imgW, 400, info, session); // Write the image map to the PrintWriter // can use a different writeImageMap to pass tooltip and URL custom ttip = new CustomOverlibToolTipTagFragmentGenerator(); toolTip = " alt='GeneChart JFreechart Plot' "; ttip.setExtra(toolTip); //must have href for area tags to have cursor:pointer ChartUtilities.writeImageMap(pw, rawFilename, info, ttip, new StandardURLTagFragmentGenerator()); info.clear(); // lose the first one info = new ChartRenderingInfo(new StandardEntityCollection()); medianFilename = ServletUtilities.saveChartAsPNG(medianChart, imgW, 400, info, session); // Write the image map to the PrintWriter // can use a different writeImageMap to pass tooltip and URL custom ttip = new CustomOverlibToolTipTagFragmentGenerator(); toolTip = " alt='GeneChart JFreechart Plot' "; ttip.setExtra(toolTip); //must have href for area tags to have cursor:pointer ChartUtilities.writeImageMap(pw, medianFilename, info, ttip, new StandardURLTagFragmentGenerator()); // ChartUtilities.writeImageMap(pw, filename, info, true); pw.flush(); } catch (Exception e) { System.out.println("Exception - " + e.toString()); e.printStackTrace(System.out); log2Filename = "public_error_500x300.png"; } // return filename; charts.put("errorBars", log2Filename); charts.put("noErrorBars", rawFilename); charts.put("medianBars", medianFilename); charts.put("bwFilename", bwFilename); charts.put("legend", legendHtml); charts.put("size", ps.toString()); return charts; }
From source file:graph.plotter.LineGraph.java
/** * This is the main working button for this class... It creates Line Graph analyZing whole data set * /*from ww w .j a va2s .c om*/ * @param evt */ private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: try { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); int i; i = 0; String genre = " "; if (button1 == 2) { if (button2 == 1) while (i < cnt) { double aa = Double.parseDouble(Table.getModel().getValueAt(i, 1).toString()); String str = Table.getModel().getValueAt(i, 0).toString(); dataset.setValue(new Double(aa), genre, str); i++; //genre+=" "; } else { try { BufferedReader br = new BufferedReader(new FileReader(jTextField4.getText())); String Line; while ((Line = br.readLine()) != null) { String[] value = Line.split(","); double val = Double.parseDouble(value[1]); dataset.setValue(new Double(val), genre, value[0]); // genre+=" "; ////System.out.println(value[0]); } } catch (FileNotFoundException ex) { Logger.getLogger(LineGraph.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LineGraph.class.getName()).log(Level.SEVERE, null, ex); } } } else if (button1 == 1) { String input = jTextField1.getText(); input = input.replaceAll("sin", "@"); input = input.replaceAll("cos", "#"); input = input.replaceAll("tan", "Q"); input = input.replaceAll("log", "~"); input = input.replaceAll("e", "&"); input = input.replaceAll("cosec", "r"); input = input.replaceAll("cot", "w"); input = input.replaceAll("sec", "y"); //System.out.println(input); int len; len = input.length(); String so = "."; for (ind = 0; ind < 360; ind++) { String gini = input; String sa = Integer.toString(ind); gini = gini.replaceAll("X", sa); Polish polish = new Polish(gini); double Calculate = Polish.Calculate(); dataset.setValue(new Double(Calculate), ".", sa); so += "."; } } JFreeChart chart = ChartFactory.createLineChart("Line Graph", "X - Axis", "Y - Axis", dataset, PlotOrientation.VERTICAL, false, true, false); CategoryPlot p = chart.getCategoryPlot(); p.setRangeGridlinePaint(Color.YELLOW); p.setBackgroundPaint(Color.BLACK); ChartFrame frame = new ChartFrame("Line Chart", chart); jButto1 = new JButton("Save"); frame.setLayout(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 1; gc.gridy = 0; panel.add(jButto1, gc); frame.add(panel, BorderLayout.SOUTH); jButto1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); final File file1 = new File("Line_Chart.png"); ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info); } catch (Exception ex) { } } }); frame.setVisible(true); frame.setSize(858, 513); } catch (Exception e) { } }