List of usage examples for org.jfree.chart.axis CategoryAxis setCategoryLabelPositions
public void setCategoryLabelPositions(CategoryLabelPositions positions)
From source file:ro.nextreports.engine.chart.JFreeChartExporter.java
private JFreeChart createBarChart(boolean horizontal, boolean stacked, boolean isCombo) throws QueryException { barDataset = new DefaultCategoryDataset(); String chartTitle = replaceParameters(chart.getTitle().getTitle()); chartTitle = StringUtil.getI18nString(chartTitle, I18nUtil.getLanguageByName(chart, language)); Object[] charts;/*w w w. j av a 2 s . c om*/ List<String> legends; Object[] lineCharts = null; String lineLegend = null; if (isCombo) { lineCharts = new Object[1]; if (chart.getYColumnsLegends().size() < chart.getYColumns().size()) { lineLegend = ""; } else { lineLegend = chart.getYColumnsLegends().get(chart.getYColumns().size() - 1); } charts = new Object[chart.getYColumns().size() - 1]; legends = chart.getYColumnsLegends().subList(0, chart.getYColumns().size() - 1); } else { charts = new Object[chart.getYColumns().size()]; legends = chart.getYColumnsLegends(); } boolean hasLegend = false; for (int i = 0; i < charts.length; i++) { String legend = ""; try { legend = replaceParameters(legends.get(i)); legend = StringUtil.getI18nString(legend, I18nUtil.getLanguageByName(chart, language)); } catch (IndexOutOfBoundsException ex) { // no legend set } // Important : must have default different legends used in barDataset.addValue if ((legend == null) || "".equals(legend.trim())) { legend = DEFAULT_LEGEND_PREFIX + String.valueOf(i + 1); } else { hasLegend = true; } charts[i] = legend; } if (isCombo) { String leg = ""; if (lineLegend != null) { leg = replaceParameters(lineLegend); } lineCharts[0] = leg; } byte style = chart.getType().getStyle(); JFreeChart jfreechart; String xLegend = StringUtil.getI18nString(replaceParameters(chart.getXLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); String yLegend = StringUtil.getI18nString(replaceParameters(chart.getYLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); PlotOrientation plotOrientation = horizontal ? PlotOrientation.HORIZONTAL : PlotOrientation.VERTICAL; if (stacked) { jfreechart = ChartFactory.createStackedBarChart(chartTitle, // chart title xLegend, // x-axis Label yLegend, // y-axis Label barDataset, // data plotOrientation, // orientation true, // include legend true, // tooltips false // URLs ); } else { switch (style) { case ChartType.STYLE_BAR_PARALLELIPIPED: case ChartType.STYLE_BAR_CYLINDER: jfreechart = ChartFactory.createBarChart3D(chartTitle, // chart title xLegend, // x-axis Label yLegend, // y-axis Label barDataset, // data plotOrientation, // orientation true, // include legend true, // tooltips false // URLs ); break; default: jfreechart = ChartFactory.createBarChart(chartTitle, // chart title xLegend, // x-axis Label yLegend, // y-axis Label barDataset, // data plotOrientation, // orientation true, // include legend true, // tooltips false // URLs ); break; } } if (style == ChartType.STYLE_BAR_CYLINDER) { ((CategoryPlot) jfreechart.getPlot()).setRenderer(new CylinderRenderer()); } // hide legend if necessary if (!hasLegend) { jfreechart.removeLegend(); } // hide border jfreechart.setBorderVisible(false); // title setTitle(jfreechart); // chart colors & values shown on bars boolean showValues = (chart.getShowYValuesOnChart() == null) ? false : chart.getShowYValuesOnChart(); CategoryPlot plot = (CategoryPlot) jfreechart.getPlot(); plot.setForegroundAlpha(transparency); BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setDrawBarOutline(false); DecimalFormat decimalformat; DecimalFormat percentageFormat; if (chart.getYTooltipPattern() == null) { decimalformat = new DecimalFormat("#"); percentageFormat = new DecimalFormat("0.00%"); } else { decimalformat = new DecimalFormat(chart.getYTooltipPattern()); percentageFormat = decimalformat; } for (int i = 0; i < charts.length; i++) { renderer.setSeriesPaint(i, chart.getForegrounds().get(i)); if (showValues) { renderer.setSeriesItemLabelsVisible(i, true); renderer.setSeriesItemLabelGenerator(i, new StandardCategoryItemLabelGenerator("{2}", decimalformat, percentageFormat)); } } if (showValues) { // increase a little bit the range axis to view all item label values over bars plot.getRangeAxis().setUpperMargin(0.2); } // grid axis visibility & colors if ((chart.getXShowGrid() != null) && !chart.getXShowGrid()) { plot.setDomainGridlinesVisible(false); } else { if (chart.getXGridColor() != null) { plot.setDomainGridlinePaint(chart.getXGridColor()); } else { plot.setDomainGridlinePaint(Color.BLACK); } } if ((chart.getYShowGrid() != null) && !chart.getYShowGrid()) { plot.setRangeGridlinesVisible(false); } else { if (chart.getYGridColor() != null) { plot.setRangeGridlinePaint(chart.getYGridColor()); } else { plot.setRangeGridlinePaint(Color.BLACK); } } // chart background plot.setBackgroundPaint(chart.getBackground()); // labels color plot.getDomainAxis().setTickLabelPaint(chart.getXColor()); plot.getRangeAxis().setTickLabelPaint(chart.getYColor()); // legend color plot.getDomainAxis().setLabelPaint(chart.getXLegend().getColor()); plot.getRangeAxis().setLabelPaint(chart.getYLegend().getColor()); // legend font plot.getDomainAxis().setLabelFont(chart.getXLegend().getFont()); plot.getRangeAxis().setLabelFont(chart.getYLegend().getFont()); // axis color plot.getDomainAxis().setAxisLinePaint(chart.getxAxisColor()); plot.getRangeAxis().setAxisLinePaint(chart.getyAxisColor()); // hide labels if ((chart.getXShowLabel() != null) && !chart.getXShowLabel()) { plot.getDomainAxis().setTickLabelsVisible(false); plot.getDomainAxis().setTickMarksVisible(false); } if ((chart.getYShowLabel() != null) && !chart.getYShowLabel()) { plot.getRangeAxis().setTickLabelsVisible(false); plot.getRangeAxis().setTickMarksVisible(false); } if (chart.getType().getStyle() == ChartType.STYLE_NORMAL) { // no shadow renderer.setShadowVisible(false); // no gradient renderer.setBarPainter(new StandardBarPainter()); } // label orientation CategoryAxis domainAxis = plot.getDomainAxis(); if (chart.getXorientation() == Chart.VERTICAL) { domainAxis .setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 2)); } else if (chart.getXorientation() == Chart.DIAGONAL) { domainAxis .setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 4)); } else if (chart.getXorientation() == Chart.HALF_DIAGONAL) { domainAxis .setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 8)); } // labels fonts domainAxis.setTickLabelFont(chart.getXLabelFont()); plot.getRangeAxis().setTickLabelFont(chart.getYLabelFont()); createChart(plot.getRangeAxis(), charts); if (isCombo) { addLineChartOverBar(jfreechart, lineCharts, lineLegend); } return jfreechart; }
From source file:lucee.runtime.tag.Chart.java
private void setLabelFormat(JFreeChart chart) { Plot plot = chart.getPlot();/*from w w w . j a v a2 s .c o m*/ if (plot instanceof CategoryPlot) { CategoryPlot cp = (CategoryPlot) plot; ValueAxis rangeAxis = cp.getRangeAxis(); rangeAxis.setAutoTickUnitSelection(true); rangeAxis.setStandardTickUnits(new TickUnitsImpl(rangeAxis.getStandardTickUnits(), labelFormat)); CategoryItemRenderer r = cp.getRenderer(); r.setBaseItemLabelsVisible(false); CategoryAxis da = cp.getDomainAxis(); if (!showXLabel) da.setTickLabelsVisible(false); da.setCategoryLabelPositions(labelPosition); da.setMaximumCategoryLabelWidthRatio(100); //da.setVisible(false); } if (plot instanceof XYPlot) { XYPlot cp = (XYPlot) plot; ValueAxis rangeAxis = cp.getRangeAxis(); rangeAxis.setAutoTickUnitSelection(true); rangeAxis.setStandardTickUnits(new TickUnitsImpl(rangeAxis.getStandardTickUnits(), labelFormat)); XYItemRenderer r = cp.getRenderer(); r.setBaseItemLabelsVisible(false); ValueAxis da = cp.getDomainAxis(); if (!_plotItemLables.isEmpty()) { _plotItemLables.add(0, ""); String[] cols = _plotItemLables.toArray(new String[_plotItemLables.size()]); SymbolAxis sa = new SymbolAxis(da.getLabel(), cols); sa.setRange(da.getRange()); if (labelPosition == LABEL_VERTICAL) { sa.setVerticalTickLabels(true); } cp.setDomainAxis(sa); } if (!showXLabel) cp.getDomainAxis().setTickLabelsVisible(false); //da.setVisible(false); } }
From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java
private boolean writeDetailedFactorAnalysis(ExpressionExperiment ee, OutputStream os) throws Exception { SVDValueObject svdo = svdService.getSvdFactorAnalysis(ee.getId()); if (svdo == null) return false; if (svdo.getFactors().isEmpty() && svdo.getDates().isEmpty()) { return false; }//www . jav a 2 s . co m Map<Integer, Map<Long, Double>> factorCorrelations = svdo.getFactorCorrelations(); // Map<Integer, Map<Long, Double>> factorPvalues = svdo.getFactorPvalues(); Map<Integer, Double> dateCorrelations = svdo.getDateCorrelations(); assert ee.getId().equals(svdo.getId()); ee = expressionExperimentService.thawLite(ee); // need the experimental design int maxWidth = 30; Map<Long, String> efs = this.getFactorNames(ee, maxWidth); Map<Long, ExperimentalFactor> efIdMap = EntityUtils .getIdMap(ee.getExperimentalDesign().getExperimentalFactors()); Collection<Long> continuousFactors = new HashSet<>(); for (ExperimentalFactor ef : ee.getExperimentalDesign().getExperimentalFactors()) { boolean isContinous = ExperimentalDesignUtils.isContinuous(ef); if (isContinous) { continuousFactors.add(ef.getId()); } } /* * Make plots of the dates vs. PCs, factors vs. PCs. */ int MAX_COMP = 3; Map<Long, List<JFreeChart>> charts = new LinkedHashMap<>(); ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme()); /* * FACTORS */ String componentShorthand = "PC"; for (Integer component : factorCorrelations.keySet()) { if (component >= MAX_COMP) break; String xaxisLabel = componentShorthand + (component + 1); for (Long efId : factorCorrelations.get(component).keySet()) { /* * Should not happen. */ if (!efs.containsKey(efId)) { log.warn("No experimental factor with id " + efId); continue; } if (!svdo.getFactors().containsKey(efId)) { // this should not happen. continue; } boolean isCategorical = !continuousFactors.contains(efId); Map<Long, String> categories = new HashMap<>(); if (isCategorical) { this.getCategories(efIdMap, efId, categories); } if (!charts.containsKey(efId)) { charts.put(efId, new ArrayList<JFreeChart>()); } Double a = factorCorrelations.get(component).get(efId); String plotname = (efs.get(efId) == null ? "?" : efs.get(efId)) + " " + xaxisLabel; // unique? if (a != null && !Double.isNaN(a)) { String title = plotname + " " + String.format("%.2f", a); List<Double> values = svdo.getFactors().get(efId); Double[] eigenGene = this.getEigenGene(svdo, component); assert values.size() == eigenGene.length; /* * Plot eigengene vs values, add correlation to the plot */ JFreeChart chart; if (isCategorical) { /* * Categorical factor */ // use the absolute value of the correlation, since direction is arbitrary. title = plotname + " " + String.format("r=%.2f", Math.abs(a)); DefaultMultiValueCategoryDataset dataset = new DefaultMultiValueCategoryDataset(); /* * What this code does is organize the factor values by the groups. */ Map<String, List<Double>> groupedValues = new TreeMap<>(); for (int i = 0; i < values.size(); i++) { Long fvId = values.get(i).longValue(); String fvValue = categories.get(fvId); if (fvValue == null) { /* * Problem ...eg gill2006fateinocean id=1748 -- missing values. We just don't plot * anything for this sample. */ continue; // is this all we need to do? } if (!groupedValues.containsKey(fvValue)) { groupedValues.put(fvValue, new ArrayList<Double>()); } groupedValues.get(fvValue).add(eigenGene[i]); if (log.isDebugEnabled()) log.debug(fvValue + " " + values.get(i)); } for (String key : groupedValues.keySet()) { dataset.add(groupedValues.get(key), plotname, key); } // don't show the name of the X axis: it's redundant with the title. NumberAxis rangeAxis = new NumberAxis(xaxisLabel); rangeAxis.setAutoRangeIncludesZero(false); // rangeAxis.setAutoRange( false ); rangeAxis.setAutoRangeMinimumSize(4.0); // rangeAxis.setRange( new Range( -2, 2 ) ); CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis(null), rangeAxis, new ScatterRenderer()); plot.setRangeGridlinesVisible(false); plot.setDomainGridlinesVisible(false); chart = new JFreeChart(title, new Font("SansSerif", Font.BOLD, 12), plot, false); ScatterRenderer renderer = (ScatterRenderer) plot.getRenderer(); float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP); renderer.setSeriesFillPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f)); renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); renderer.setUseOutlinePaint(false); renderer.setUseFillPaint(true); renderer.setBaseFillPaint(Color.white); CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); } else { /* * Continuous value factor */ DefaultXYDataset series = new DefaultXYDataset(); series.addSeries(plotname, new double[][] { ArrayUtils.toPrimitive(values.toArray(new Double[] {})), ArrayUtils.toPrimitive(eigenGene) }); // don't show x-axis label, which would otherwise be efs.get( efId ) chart = ChartFactory.createScatterPlot(title, null, xaxisLabel, series, PlotOrientation.VERTICAL, false, false, false); XYPlot plot = chart.getXYPlot(); plot.setRangeGridlinesVisible(false); plot.setDomainGridlinesVisible(false); XYItemRenderer renderer = plot.getRenderer(); renderer.setBasePaint(Color.white); renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP); renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f)); plot.setRenderer(renderer); } chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12)); charts.get(efId).add(chart); } } } /* * DATES */ charts.put(-1L, new ArrayList<JFreeChart>()); for (Integer component : dateCorrelations.keySet()) { String xaxisLabel = componentShorthand + (component + 1); List<Date> dates = svdo.getDates(); if (dates.isEmpty()) break; long secspan = ubic.basecode.util.DateUtil.numberOfSecondsBetweenDates(dates); if (component >= MAX_COMP) break; Double a = dateCorrelations.get(component); if (a != null && !Double.isNaN(a)) { Double[] eigenGene = svdo.getvMatrix().getColObj(component); /* * Plot eigengene vs values, add correlation to the plot */ TimeSeries series = new TimeSeries("Dates vs. eigen" + (component + 1)); int i = 0; for (Date d : dates) { // if span is less than an hour, retain the minute. if (secspan < 60 * 60) { series.addOrUpdate(new Minute(d), eigenGene[i++]); } else { series.addOrUpdate(new Hour(d), eigenGene[i++]); } } TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createTimeSeriesChart( "Dates: " + xaxisLabel + " " + String.format("r=%.2f", a), null, xaxisLabel, dataset, false, false, false); XYPlot xyPlot = chart.getXYPlot(); chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12)); // standard renderer makes lines. XYDotRenderer renderer = new XYDotRenderer(); renderer.setBaseFillPaint(Color.white); renderer.setDotHeight(3); renderer.setDotWidth(3); renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); // has no effect, need dotheight. float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP); renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f)); ValueAxis domainAxis = xyPlot.getDomainAxis(); domainAxis.setVerticalTickLabels(true); xyPlot.setRenderer(renderer); xyPlot.setRangeGridlinesVisible(false); xyPlot.setDomainGridlinesVisible(false); charts.get(-1L).add(chart); } } /* * Plot in a grid, with each factor as a column. FIXME What if we have too many factors to fit on the screen? */ int columns = (int) Math.ceil(charts.size()); int perChartSize = ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX; BufferedImage image = new BufferedImage(columns * perChartSize, MAX_COMP * perChartSize, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); int currentX = 0; int currentY = 0; for (Long id : charts.keySet()) { for (JFreeChart chart : charts.get(id)) { this.addChartToGraphics(chart, g2, currentX, currentY, perChartSize, perChartSize); if (currentY + perChartSize < MAX_COMP * perChartSize) { currentY += perChartSize; } else { currentY = 0; currentX += perChartSize; } } } os.write(ChartUtilities.encodeAsPNG(image)); return true; }
From source file:hudson.model.Job.java
public Graph getBuildTimeGraph() { return new Graph(getLastBuildTime(), 500, 400) { @Override//w w w . jav a2 s .c o m protected JFreeChart createGraph() { class ChartLabel implements Comparable<ChartLabel> { final Run run; public ChartLabel(Run r) { this.run = r; } public int compareTo(ChartLabel that) { return this.run.number - that.run.number; } @Override public boolean equals(Object o) { // HUDSON-2682 workaround for Eclipse compilation bug // on (c instanceof ChartLabel) if (o == null || !ChartLabel.class.isAssignableFrom(o.getClass())) { return false; } ChartLabel that = (ChartLabel) o; return run == that.run; } public Color getColor() { // TODO: consider gradation. See // http://www.javadrive.jp/java2d/shape/index9.html Result r = run.getResult(); if (r == Result.FAILURE) return ColorPalette.RED; else if (r == Result.UNSTABLE) return ColorPalette.YELLOW; else if (r == Result.ABORTED || r == Result.NOT_BUILT) return ColorPalette.GREY; else return ColorPalette.BLUE; } @Override public int hashCode() { return run.hashCode(); } @Override public String toString() { String l = run.getDisplayName(); if (run instanceof Build) { String s = ((Build) run).getBuiltOnStr(); if (s != null) l += ' ' + s; } return l; } } DataSetBuilder<String, ChartLabel> data = new DataSetBuilder<String, ChartLabel>(); for (Run r : getNewBuilds()) { if (r.isBuilding()) continue; data.add(((double) r.getDuration()) / (1000 * 60), "min", new ChartLabel(r)); } final CategoryDataset dataset = data.build(); final JFreeChart chart = ChartFactory.createStackedAreaChart(null, // chart // title null, // unused Messages.Job_minutes(), // range axis label dataset, // data PlotOrientation.VERTICAL, // orientation false, // include legend true, // tooltips false // urls ); chart.setBackgroundPaint(Color.white); final CategoryPlot plot = chart.getCategoryPlot(); // plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0)); plot.setBackgroundPaint(Color.WHITE); plot.setOutlinePaint(null); plot.setForegroundAlpha(0.8f); // plot.setDomainGridlinesVisible(true); // plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.black); CategoryAxis domainAxis = new ShiftedCategoryAxis(null); plot.setDomainAxis(domainAxis); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90); domainAxis.setLowerMargin(0.0); domainAxis.setUpperMargin(0.0); domainAxis.setCategoryMargin(0.0); final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); ChartUtil.adjustChebyshev(dataset, rangeAxis); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); StackedAreaRenderer ar = new StackedAreaRenderer2() { @Override public Paint getItemPaint(int row, int column) { ChartLabel key = (ChartLabel) dataset.getColumnKey(column); return key.getColor(); } @Override public String generateURL(CategoryDataset dataset, int row, int column) { ChartLabel label = (ChartLabel) dataset.getColumnKey(column); return String.valueOf(label.run.number); } @Override public String generateToolTip(CategoryDataset dataset, int row, int column) { ChartLabel label = (ChartLabel) dataset.getColumnKey(column); return label.run.getDisplayName() + " : " + label.run.getDurationString(); } }; plot.setRenderer(ar); // crop extra space around the graph plot.setInsets(new RectangleInsets(0, 0, 0, 5.0)); return chart; } }; }
From source file:skoa.helpers.Graficos.java
private void barras() { unificarDatosFicheros();/*w w w . j a v a 2 s . c om*/ Vector<String> vectorOrdenUnidades = new Vector<String>(); vectorOrdenUnidades = ordenDeUnidades(); aplicarDiferencia(vectorOrdenUnidades); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset = obtenerSerieBarras(vectorOrdenUnidades); String unidad = ""; //for (int i=0;i<vectorOrdenUnidades.size();i++) unidad=unidad+vectorOrdenUnidades.elementAt(i)+", "; for (int i = 0; i < vectorOrdenUnidades.size(); i++) { if (vectorOrdenUnidades.elementAt(i).indexOf("W") >= 0 || vectorOrdenUnidades.elementAt(i).indexOf("L") >= 0 || vectorOrdenUnidades.elementAt(i).indexOf("m") >= 0 || vectorOrdenUnidades.elementAt(i).indexOf("B") >= 0) unidad = unidad + vectorOrdenUnidades.elementAt(i) + ", "; else if (vectorOrdenUnidades.elementAt(i).indexOf("C") >= 0) unidad = unidad + "C, "; else unidad = unidad + ", "; } unidad = unidad.substring(0, unidad.length() - 2); //Quita el ultimo espacio y la ultima coma. JFreeChart grafica = ChartFactory.createBarChart("Valores medidos de las direcciones de grupo", "Fechas", //titulo eje x "Mediciones (" + unidad + ")", dataset, PlotOrientation.VERTICAL, true, //leyenda true, false); if (fechaInicial.isEmpty()) { fechaInicial = fechaFinal = "?"; } TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal, new Font("SanSerif", Font.ITALIC, 12)); grafica.addSubtitle(t); CategoryPlot plot = grafica.getCategoryPlot(); //Modificar eje X CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)); domainAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 8)); //Letra de las fechas ms pequea //Esconder las sombras de las barras del barchart. CategoryPlot categoryPlot = (CategoryPlot) grafica.getPlot(); BarRenderer renderer = new BarRenderer(); renderer.setShadowVisible(false); categoryPlot.setRenderer(renderer); //------------------------------------------------- try { ChartUtilities.saveChartAsJPEG(new File(ruta + "BarrasSmall.jpg"), grafica, 400, 300); ChartUtilities.saveChartAsJPEG(new File(ruta + "BarrasBig.jpg"), grafica, 900, 600); } catch (IOException e) { System.err.println("Problem occurred creating chart."); } }
From source file:skoa.helpers.Graficos.java
/********************************************************************************************************* * FUNCIONES PARA CREAR LOS GRFICOS DE LA CONSULTA C! MANIPULANDO LOS DATOS OBTENIDOS DE LAS CONSULTAS.* *********************************************************************************************************/ private void maxMinMed() { //En este tipo de consultas, sacamos la DG del fichero original de datos, para ponerla en la graf. String dg = nombresFicheros.get(0); //dg=dg.substring(dg.indexOf("-")+7,dg.indexOf(".txt")); //Saca la DG del nombre del fich. if (dg.indexOf("D") > 0 && dg.indexOf(" ") < 0) { //Si es el resultado final de una consulta D. dg = dg.substring(dg.indexOf(".txt") - 13, dg.indexOf(".txt")); //Saca la DG del nombre del fich. } else { //Si son resultados de una consulta D. //As, buscando a partir de .txt da igual el tipo de consulta que sea, que se saca igual. dg = dg.substring(dg.indexOf(" ") - 6, dg.indexOf(".txt")); //Saca la DG del nombre del fich. }//from w w w. ja va 2 s . c om //--------------------------------------------- crearEstadisticas(); //Crea el fichero estadisticas.txt donde se encuentra el FECHA MAX MIN y MED en este orden Vector<String> vectorOrdenUnidades = new Vector<String>(); vectorOrdenUnidades.add(unidad); nombresDGs.add("Max"); //Reusamos esta variable. Nos referimos al nombre de cada una de las barras que se ven. nombresDGs.add("Min"); nombresDGs.add("Med"); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset = obtenerSerieBarras2(vectorOrdenUnidades); String unidad = ""; for (int i = 0; i < vectorOrdenUnidades.size(); i++) unidad = unidad + vectorOrdenUnidades.elementAt(i) + ", "; unidad = unidad.substring(0, unidad.length() - 2); //Quita el ultimo espacio y la ultima coma. if (unidad.indexOf("C") >= 0) unidad = "C"; dg = dg.replaceAll("-", "/"); JFreeChart grafica = ChartFactory.createBarChart("Valores medidos de las direcciones de grupo", "Fechas", //titulo eje x "Mediciones (" + unidad + ") de " + dg, dataset, PlotOrientation.VERTICAL, true, //leyenda true, false); if (fechaInicial.equals("") & fechaFinal.equals("")) { //Si estn vacas es porque no hay resultados para ese intervalo. fechaInicial = " ? "; fechaFinal = " ? "; } TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal, new Font("SanSerif", Font.ITALIC, 12)); grafica.addSubtitle(t); CategoryPlot plot = grafica.getCategoryPlot(); CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)); domainAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 9)); //Letra de las fechas ms pequea //Esconder las sombras de las barras del barchart. CategoryPlot categoryPlot = (CategoryPlot) grafica.getPlot(); BarRenderer renderer = new BarRenderer(); renderer.setShadowVisible(false); categoryPlot.setRenderer(renderer); //------------------------------------------------- try { ChartUtilities.saveChartAsJPEG(new File(ruta + "MaxMinMedSmall.jpg"), grafica, 400, 300); ChartUtilities.saveChartAsJPEG(new File(ruta + "MaxMinMedBig.jpg"), grafica, 900, 600); } catch (IOException e) { System.err.println("Problem occurred creating chart." + e); } }
From source file:org.hxzon.demo.jfreechart.CategoryDatasetDemo2.java
private static JFreeChart createBarChart(CategoryDataset dataset) { CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel); ValueAxis valueAxis = new NumberAxis(valueAxisLabel); BarRenderer renderer = new BarRenderer(); if (orientation == PlotOrientation.HORIZONTAL) { ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER_LEFT); renderer.setBasePositiveItemLabelPosition(position1); ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_RIGHT); renderer.setBaseNegativeItemLabelPosition(position2); } else if (orientation == PlotOrientation.VERTICAL) { ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER); renderer.setBasePositiveItemLabelPosition(position1); ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER); renderer.setBaseNegativeItemLabelPosition(position2); }/*from w w w .j a v a 2 s. co m*/ if (tooltips) { renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); } if (urls) { renderer.setBaseItemURLGenerator(new StandardCategoryURLGenerator()); } CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer); plot.setOrientation(orientation); JFreeChart chart = new JFreeChart("Bar Chart Demo 1", JFreeChart.DEFAULT_TITLE_FONT, plot, legend); chart.setBackgroundPaint(Color.white); valueAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); renderer.setDrawBarOutline(false); GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64)); GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, new Color(0, 64, 0)); GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, new Color(64, 0, 0)); renderer.setSeriesPaint(0, gp0); renderer.setSeriesPaint(1, gp1); renderer.setSeriesPaint(2, gp2); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); categoryAxis .setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)); return chart; }
From source file:org.operamasks.faces.render.graph.ChartRenderer.java
private void setCategoryAxisStyles(CategoryAxis axis, UIAxis comp) { Double lowerMargin = comp.getLowerMargin(); Double upperMargin = comp.getUpperMargin(); if (lowerMargin != null) axis.setLowerMargin(lowerMargin); if (upperMargin != null) axis.setUpperMargin(upperMargin); Double labelAngle = comp.getLabelAngle(); if (labelAngle != null) { CategoryLabelPositions clp;/*from ww w .j ava 2s .c o m*/ double angle = Math.PI * labelAngle / 180.0; if (angle >= 0) { clp = CategoryLabelPositions.createDownRotationLabelPositions(angle); } else { clp = CategoryLabelPositions.createUpRotationLabelPositions(-angle); } axis.setCategoryLabelPositions(clp); } }
From source file:org.pentaho.chart.plugin.jfreechart.JFreeChartFactoryEngine.java
private void initCategoryPlot(JFreeChart chart, ChartModel chartModel, final IChartLinkGenerator linkGenerator) { initPlot(chart, chartModel);// w ww . j a v a 2s. c o m org.pentaho.chart.model.TwoAxisPlot twoAxisPlot = (org.pentaho.chart.model.TwoAxisPlot) chartModel .getPlot(); CategoryPlot categoryPlot = chart.getCategoryPlot(); Grid grid = twoAxisPlot.getGrid(); if (twoAxisPlot.getOrientation() != Orientation.HORIZONTAL) { Color color = (grid.getVerticalLineColor() != null ? new Color(0x00FFFFFF & grid.getVerticalLineColor()) : new Color(0x00FFFFFF & Grid.DEFAULT_GRID_COLOR)); categoryPlot.setDomainGridlinesVisible(grid.getVerticalLinesVisible()); categoryPlot.setDomainGridlinePaint(color); color = (grid.getHorizontalLineColor() != null ? new Color(0x00FFFFFF & grid.getHorizontalLineColor()) : new Color(0x00FFFFFF & Grid.DEFAULT_GRID_COLOR)); categoryPlot.setRangeGridlinesVisible(grid.getHorizontalLinesVisible()); categoryPlot.setRangeGridlinePaint(color); } else { Color color = (grid.getHorizontalLineColor() != null ? new Color(0x00FFFFFF & grid.getHorizontalLineColor()) : new Color(0x00FFFFFF & Grid.DEFAULT_GRID_COLOR)); categoryPlot.setDomainGridlinesVisible(grid.getHorizontalLinesVisible()); categoryPlot.setDomainGridlinePaint(color); color = (grid.getVerticalLineColor() != null ? new Color(0x00FFFFFF & grid.getVerticalLineColor()) : new Color(0x00FFFFFF & Grid.DEFAULT_GRID_COLOR)); categoryPlot.setRangeGridlinesVisible(grid.getVerticalLinesVisible()); categoryPlot.setRangeGridlinePaint(color); } categoryPlot.setDomainGridlineStroke(new BasicStroke(1)); categoryPlot.setRangeGridlineStroke(new BasicStroke(1)); List<Integer> colors = getPlotColors(twoAxisPlot); for (int j = 0; j < categoryPlot.getDatasetCount(); j++) { if (linkGenerator != null) { categoryPlot.getRenderer(j).setBaseItemURLGenerator(new CategoryURLGenerator() { public String generateURL(CategoryDataset dataset, int series, int category) { return linkGenerator.generateLink(dataset.getRowKey(series).toString(), dataset.getColumnKey(category).toString(), dataset.getValue(series, category)); } }); } for (int i = 0; i < colors.size(); i++) { categoryPlot.getRenderer(j).setSeriesPaint(i, new Color(0x00FFFFFF & colors.get(i))); } } Font domainAxisFont = ChartUtils.getFont(twoAxisPlot.getDomainAxis().getFontFamily(), twoAxisPlot.getDomainAxis().getFontStyle(), twoAxisPlot.getDomainAxis().getFontWeight(), twoAxisPlot.getDomainAxis().getFontSize()); Font rangeAxisFont = ChartUtils.getFont(twoAxisPlot.getRangeAxis().getFontFamily(), twoAxisPlot.getRangeAxis().getFontStyle(), twoAxisPlot.getRangeAxis().getFontWeight(), twoAxisPlot.getRangeAxis().getFontSize()); Font rangeTitleFont = ChartUtils.getFont(twoAxisPlot.getRangeAxis().getLegend().getFontFamily(), twoAxisPlot.getRangeAxis().getLegend().getFontStyle(), twoAxisPlot.getRangeAxis().getLegend().getFontWeight(), twoAxisPlot.getRangeAxis().getLegend().getFontSize()); Font domainTitleFont = ChartUtils.getFont(twoAxisPlot.getDomainAxis().getLegend().getFontFamily(), twoAxisPlot.getDomainAxis().getLegend().getFontStyle(), twoAxisPlot.getDomainAxis().getLegend().getFontWeight(), twoAxisPlot.getDomainAxis().getLegend().getFontSize()); CategoryAxis domainAxis = categoryPlot.getDomainAxis(); ValueAxis rangeAxis = categoryPlot.getRangeAxis(); AxesLabels axesLabels = getAxesLabels(chartModel); if ((axesLabels.rangeAxisLabel.length() > 0) && (rangeTitleFont != null)) { rangeAxis.setLabelFont(rangeTitleFont); } if ((axesLabels.domainAxisLabel.length() > 0) && (domainTitleFont != null)) { domainAxis.setLabelFont(domainTitleFont); } LabelOrientation labelOrientation = twoAxisPlot.getHorizontalAxis().getLabelOrientation(); if ((labelOrientation != null) && (labelOrientation != LabelOrientation.HORIZONTAL)) { if (twoAxisPlot.getOrientation() == Orientation.HORIZONTAL) { if (labelOrientation == LabelOrientation.VERTICAL) { rangeAxis.setVerticalTickLabels(true); } } else { switch (labelOrientation) { case VERTICAL: domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90); break; case DIAGONAL: domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); break; } } } if (domainAxisFont != null) { domainAxis.setTickLabelFont(domainAxisFont); } if (rangeAxisFont != null) { rangeAxis.setTickLabelFont(rangeAxisFont); } Number rangeMin = twoAxisPlot.getRangeAxis().getMinValue(); if (rangeMin != null) { rangeAxis.setLowerBound(rangeMin.doubleValue()); } Number rangeMax = twoAxisPlot.getRangeAxis().getMaxValue(); if (rangeMax != null) { rangeAxis.setUpperBound(rangeMax.doubleValue()); } }
From source file:org.pentaho.plugin.jfreereport.reportcharts.CategoricalChartExpression.java
protected void configureChart(final JFreeChart chart) { super.configureChart(chart); final CategoryPlot cpl = chart.getCategoryPlot(); final CategoryItemRenderer renderer = cpl.getRenderer(); if (StringUtils.isEmpty(getTooltipFormula()) == false) { renderer.setBaseToolTipGenerator( new FormulaCategoryTooltipGenerator(getRuntime(), getTooltipFormula())); }// w ww . ja va 2 s . c om if (StringUtils.isEmpty(getUrlFormula()) == false) { renderer.setBaseItemURLGenerator(new FormulaCategoryURLGenerator(getRuntime(), getUrlFormula())); } if (this.categoricalLabelFormat != null) { final StandardCategoryItemLabelGenerator scilg; if (categoricalLabelDecimalFormat != null) { final DecimalFormat numFormat = new DecimalFormat(categoricalLabelDecimalFormat, new DecimalFormatSymbols(getRuntime().getResourceBundleFactory().getLocale())); numFormat.setRoundingMode(RoundingMode.HALF_UP); scilg = new StandardCategoryItemLabelGenerator(categoricalLabelFormat, numFormat); } else if (categoricalLabelDateFormat != null) { scilg = new StandardCategoryItemLabelGenerator(categoricalLabelFormat, new SimpleDateFormat( categoricalLabelDateFormat, getRuntime().getResourceBundleFactory().getLocale())); } else { final DecimalFormat formatter = new DecimalFormat(); formatter.setDecimalFormatSymbols( new DecimalFormatSymbols(getRuntime().getResourceBundleFactory().getLocale())); scilg = new StandardCategoryItemLabelGenerator(categoricalLabelFormat, formatter); } renderer.setBaseItemLabelGenerator(scilg); } renderer.setBaseItemLabelsVisible(Boolean.TRUE.equals(getItemsLabelVisible())); if (getItemLabelFont() != null) { renderer.setBaseItemLabelFont(getItemLabelFont()); } if (categoricalItemLabelRotation != null) { final ItemLabelPosition orgPosItemLabelPos = renderer.getBasePositiveItemLabelPosition(); if (orgPosItemLabelPos == null) { final ItemLabelPosition pos2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER, TextAnchor.CENTER, categoricalItemLabelRotation.doubleValue()); renderer.setBasePositiveItemLabelPosition(pos2); } else { final ItemLabelPosition pos2 = new ItemLabelPosition(orgPosItemLabelPos.getItemLabelAnchor(), orgPosItemLabelPos.getTextAnchor(), orgPosItemLabelPos.getRotationAnchor(), categoricalItemLabelRotation.doubleValue()); renderer.setBasePositiveItemLabelPosition(pos2); } final ItemLabelPosition orgNegItemLabelPos = renderer.getBaseNegativeItemLabelPosition(); if (orgNegItemLabelPos == null) { final ItemLabelPosition pos2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER, TextAnchor.CENTER, categoricalItemLabelRotation.doubleValue()); renderer.setBaseNegativeItemLabelPosition(pos2); } else { final ItemLabelPosition neg2 = new ItemLabelPosition(orgNegItemLabelPos.getItemLabelAnchor(), orgNegItemLabelPos.getTextAnchor(), orgNegItemLabelPos.getRotationAnchor(), categoricalItemLabelRotation.doubleValue()); renderer.setBaseNegativeItemLabelPosition(neg2); } } final Font labelFont = Font.decode(getLabelFont()); final CategoryAxis categoryAxis = cpl.getDomainAxis(); categoryAxis.setLabelFont(labelFont); categoryAxis.setTickLabelFont(labelFont); if (getCategoryTitleFont() != null) { categoryAxis.setLabelFont(getCategoryTitleFont()); } if (getCategoryTickFont() != null) { categoryAxis.setTickLabelFont(getCategoryTickFont()); } if (maxCategoryLabelWidthRatio != null) { categoryAxis.setMaximumCategoryLabelWidthRatio(maxCategoryLabelWidthRatio.floatValue()); } cpl.setDomainGridlinesVisible(showGridlines); if (labelRotation != null) { double angle = labelRotation.doubleValue(); CategoryLabelPosition top = createUpRotationCategoryLabelPosition(PlaneDirection.TOP, angle); CategoryLabelPosition bottom = createUpRotationCategoryLabelPosition(PlaneDirection.BOTTOM, angle); CategoryLabelPosition left = createUpRotationCategoryLabelPosition(PlaneDirection.LEFT, angle); CategoryLabelPosition right = createUpRotationCategoryLabelPosition(PlaneDirection.RIGHT, angle); CategoryLabelPositions rotationLabelPositions = new CategoryLabelPositions(top, bottom, left, right); categoryAxis.setCategoryLabelPositions(rotationLabelPositions); } final String[] colors = getSeriesColor(); for (int i = 0; i < colors.length; i++) { renderer.setSeriesPaint(i, parseColorFromString(colors[i])); } if (lowerMargin != null) { categoryAxis.setLowerMargin(lowerMargin.doubleValue()); } if (upperMargin != null) { categoryAxis.setUpperMargin(upperMargin.doubleValue()); } if (categoryMargin != null) { categoryAxis.setCategoryMargin(categoryMargin.doubleValue()); } configureRangeAxis(cpl, labelFont); }