Example usage for org.jfree.chart JFreeChart createBufferedImage

List of usage examples for org.jfree.chart JFreeChart createBufferedImage

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart createBufferedImage.

Prototype

public BufferedImage createBufferedImage(int width, int height) 

Source Link

Document

Creates and returns a buffered image into which the chart has been drawn.

Usage

From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java

private byte[] generatePieChart(String siteId, PieDataset dataset, int width, int height, boolean render3d,
        float transparency, boolean smallFontInDomainAxis) {
    JFreeChart chart = null;
    if (render3d)
        chart = ChartFactory.createPieChart3D(null, dataset, false, false, false);
    else// www .  j a v  a  2 s  .  c  om
        chart = ChartFactory.createPieChart(null, dataset, false, false, false);
    PiePlot plot = (PiePlot) chart.getPlot();

    // set start angle (135 or 150 deg so minor data has more space on the left)
    plot.setStartAngle(150D);

    // set transparency
    plot.setForegroundAlpha(transparency);

    // set background
    chart.setBackgroundPaint(parseColor(M_sm.getChartBackgroundColor()));
    plot.setBackgroundPaint(parseColor(M_sm.getChartBackgroundColor()));

    // fix border offset      
    chart.setPadding(new RectangleInsets(5, 5, 5, 5));
    plot.setInsets(new RectangleInsets(1, 1, 1, 1));
    // set chart border
    plot.setOutlinePaint(null);
    chart.setBorderVisible(true);
    chart.setBorderPaint(parseColor("#cccccc"));

    // set antialias
    chart.setAntiAlias(true);

    BufferedImage img = chart.createBufferedImage(width, height);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        LOG.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:org.squale.squaleweb.applicationlayer.action.results.project.ProjectResultsAction.java

/**
 * Prsente les rsultats rsums du projet.
 * //from  w  ww. j av  a 2 s . c  o m
 * @param pMapping le mapping.
 * @param pForm le formulaire  lire.
 * @param pRequest la requte HTTP.
 * @param pResponse la rponse de la servlet.
 * @return l'action  raliser.
 */
public ActionForward summary(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest,
        HttpServletResponse pResponse) {

    ActionForward forward = null;
    ActionErrors errors = new ActionErrors();
    Long currentAuditId = null, previousAuditId = null;
    try {
        forward = init(pMapping, pRequest, pForm);
        if (null == forward) {
            if (getSummary(pRequest, pForm)) {
                // Rcupration des donnes permettant la gnration du Kiviat du projet
                // On rcupre le projet
                ComponentDTO project = (ComponentDTO) pRequest.getSession()
                        .getAttribute(BaseDispatchAction.PROJECT_DTO);
                AuditDTO audit = (AuditDTO) pRequest.getSession()
                        .getAttribute(BaseDispatchAction.CURRENT_AUDIT_DTO);
                AuditDTO previousAudit = (AuditDTO) pRequest.getSession()
                        .getAttribute(BaseDispatchAction.CURRENT_AUDIT_DTO);
                if (project != null && audit != null) {
                    // Rcupration du paramtre : tous les facteurs ou seuls les facteurs ayant une note ?
                    ProjectSummaryForm projectSummaryForm = (ProjectSummaryForm) pForm;
                    boolean pAllFactors = projectSummaryForm.isAllFactors();
                    // On met cette valeur en session
                    pRequest.getSession().setAttribute(ALL_FACTORS, new Boolean(pAllFactors));
                    // Prparation de l'appel  la couche mtier
                    IApplicationComponent ac = AccessDelegateHelper.getInstance("Graph");
                    Long projectId = new Long(project.getID());
                    currentAuditId = new Long(audit.getID());

                    Object[] paramsKiviat = { projectId, currentAuditId, String.valueOf(pAllFactors) };

                    // Recherche des donnes utiles  la gnration du Kiviat
                    // Recherche des donnes Kiviat
                    KiviatMaker maker = new KiviatMaker();
                    Object[] kiviatObject = (Object[]) ac.execute("getProjectKiviatGraph", paramsKiviat);
                    Map projectsValues = (Map) kiviatObject[0];
                    Boolean displayCheckBoxFactors = (Boolean) kiviatObject[1];
                    projectSummaryForm.setDisplayCheckBoxFactors(displayCheckBoxFactors);

                    Set keysSet = projectsValues.keySet();
                    Iterator it = keysSet.iterator();
                    while (it.hasNext()) {
                        String key = (String) it.next();
                        maker.addValues(key, (SortedMap) projectsValues.get(key), pRequest);
                    }
                    JFreeChart chartKiviat = maker.getChart();
                    ChartRenderingInfo infoKiviat = new ChartRenderingInfo(new StandardEntityCollection());
                    // Sauvegarde de l'image du Kiviat au format png dans un espace temporaire
                    String fileNameKiviat = ServletUtilities.saveChartAsPNG(chartKiviat,
                            KiviatMaker.DEFAULT_WIDTH, KiviatMaker.DEFAULT_HEIGHT, infoKiviat,
                            pRequest.getSession());
                    GraphMaker projectKiviatChart = new GraphMaker(pRequest, fileNameKiviat, infoKiviat);

                    // Pour l'export pdf en attendant de mettre les graphe dans les formulaires
                    pRequest.getSession().removeAttribute("kiviatChart");
                    pRequest.getSession().setAttribute("kiviatChart", chartKiviat
                            .createBufferedImage(KiviatMaker.DEFAULT_WIDTH, KiviatMaker.DEFAULT_HEIGHT));

                    ((ProjectSummaryForm) pForm).setKiviat(projectKiviatChart);
                    ((ProjectSummaryForm) pForm).setTags(project.getTags());
                }
                forward = pMapping.findForward("summary");
            } else { // Aucun audit, redirige vers la page courante
                forward = pMapping.findForward("noAudits");
            }
        }
    } catch (Exception e) {
        // Factorisation du traitement des exceptions
        handleException(e, errors, pRequest);
    }
    if (!errors.isEmpty()) {
        // Enregistrement des messages
        saveMessages(pRequest, errors);
        // Routage vers la page d'erreur
        forward = pMapping.findForward("total_failure");
    }
    // Mise en place du traceur historique
    updateHistTracker(WebMessages.getString(pRequest, "tracker.synthesis"), "project.do?action=summary",
            TrackerStructure.UNDEFINED, pRequest, true);
    // Indique que l'on vient d'une vue synthse et pas d'une vue composant
    changeWay(pRequest, "false");
    return forward;
}

From source file:org.getobjects.samples.HelloChart.Main.java

/**
 * This defines the direct action which can be invoked using:<pre>
 *   /HelloThumbnail/wa/Main/chart?chs=128x128&chartType=p3</pre>
 * //from  ww w.  jav  a  2 s .c  o m
 * <p>
 * Note that the method returns a java.awt.BufferedImage. This will get
 * rendered to a GIF image by the GoDefaultRenderer.
 * (this method does not return a WOResponse, but it lets the Go machinery
 * deal with the image result object). 
 * 
 * @return a BufferedImage containing the scaled image
 */
public Object chartAction() {
    Dimension size = UGoogleChart.getDimensions(F("chs", "128x128"), null);
    String chartType = (String) F("cht", "p");

    JFreeChart chart = null;
    if (chartType.equals("p")) {
        chart = ChartFactory.createPieChart((String) F("title", "Revenue Chart" /* default title */),
                this.getPieDataset(), UObject.boolValue(F("legend", true)) /* show legend */,
                UObject.boolValue(F("tooltips", true)) /* show tooltips */, false /* no URLs */);
    } else if (chartType.equals("p3")) {
        chart = ChartFactory.createPieChart3D((String) F("title", "Revenue Chart" /* default title */),
                this.getPieDataset(), UObject.boolValue(F("legend", true)) /* show legend */,
                UObject.boolValue(F("tooltips", true)) /* show tooltips */, false /* no URLs */);
    } else if (chartType.startsWith("b")) {
        // bhs, bvs (one bar with multiple values)
        // bhg, bvg (one bar for each row)

        PlotOrientation orientation = PlotOrientation.VERTICAL;
        if (chartType.startsWith("bh"))
            orientation = PlotOrientation.HORIZONTAL;

        if (chartType.endsWith("3")) {
            chart = ChartFactory.createBarChart3D((String) F("title", "Revenue Chart" /* default title */),
                    (String) F("xlabel", "X-Axis"), (String) F("ylabel", "Y-Axis"), getCatDataSet(),
                    orientation, UObject.boolValue(F("legend", true)) /* show legend */,
                    UObject.boolValue(F("tooltips", true)) /* show tooltips */, false /* no URLs */);
        } else {
            chart = ChartFactory.createBarChart((String) F("title", "Revenue Chart" /* default title */),
                    (String) F("xlabel", "X-Axis"), (String) F("ylabel", "Y-Axis"), getRevCatDataSet(),
                    orientation, UObject.boolValue(F("legend", true)) /* show legend */,
                    UObject.boolValue(F("tooltips", true)) /* show tooltips */, false /* no URLs */);
        }
    }

    /* style the chart */

    chart.setBorderVisible(true);
    //chart.setBorderPaint(new Paint(Color.blue));

    Paint p = new GradientPaint(0, 0, Color.white, 1000, 0, Color.blue);
    chart.setBackgroundPaint(p);

    /* style the plot */

    Plot plot = chart.getPlot();
    plot.setBackgroundPaint(new Color(240, 240, 250));

    /* add explosion for Pies */

    if (plot instanceof PiePlot) {
        PiePlot pplot = (PiePlot) chart.getPlot();
        pplot.setExplodePercent("Products", 0.30); // can be multiple explodes
    }

    /* create the image for HTTP delivery */

    return chart.createBufferedImage(size.width, size.height);
}

From source file:org.geopublishing.atlasStyler.classification.FeatureClassification.java

@Override
public BufferedImage createHistogramImage(boolean showMean, boolean showSd, int histogramBins,
        String label_xachsis) throws InterruptedException, IOException {
    HistogramDataset hds = new HistogramDataset();
    DoubleArrayList valuesAL;// w  w  w .  j a v a  2s .  c o  m
    valuesAL = getStatistics().elements();
    // new double[] {0.4,3,4,2,5.,22.,4.,2.,33.,12.}
    double[] elements = Arrays.copyOf(valuesAL.elements(), getStatistics().size());
    hds.addSeries(1, elements, histogramBins);

    /** Statically label the Y Axis **/
    String label_yachsis = ASUtil.R("QuantitiesClassificationGUI.Histogram.YAxisLabel");

    JFreeChart chart = org.jfree.chart.ChartFactory.createHistogram(null, label_xachsis, label_yachsis, hds,
            PlotOrientation.VERTICAL, false, true, true);

    /***********************************************************************
     * Paint the classes into the JFreeChart
     */
    int countLimits = 0;
    for (Double cLimit : getClassLimits()) {
        ValueMarker marker = new ValueMarker(cLimit);
        XYPlot plot = chart.getXYPlot();
        marker.setPaint(Color.orange);
        marker.setLabel(String.valueOf(countLimits));
        marker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
        marker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        plot.addDomainMarker(marker);

        countLimits++;
    }

    /***********************************************************************
     * Optionally painting SD and MEAN into the histogram
     */
    try {
        if (showSd) {
            ValueMarker marker;
            marker = new ValueMarker(getStatistics().standardDeviation(), Color.green.brighter(),
                    new BasicStroke(1.5f));
            XYPlot plot = chart.getXYPlot();
            marker.setLabel(ASUtil.R("QuantitiesClassificationGUI.Histogram.SD.ShortLabel"));
            marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
            marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
            plot.addDomainMarker(marker);
        }

        if (showMean) {
            ValueMarker marker;
            marker = new ValueMarker(getStatistics().mean(), Color.green.darker(), new BasicStroke(1.5f));
            XYPlot plot = chart.getXYPlot();
            marker.setLabel(ASUtil.R("QuantitiesClassificationGUI.Histogram.Mean.ShortLabel"));
            marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
            marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
            plot.addDomainMarker(marker);
        }

    } catch (Exception e) {
        LOGGER.error("Painting SD and MEAN into the histogram", e);
    }

    /***********************************************************************
     * Render the Chart
     */
    BufferedImage image = chart.createBufferedImage(400, 200);

    return image;
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

private void renderChartInfo() {
    HashMap<Object, Marker> marks = new HashMap<>();
    DefaultPieDataset dataset = buildDataset(marks);

    JFreeChart chart = ChartFactory.createPieChart(null, // chart title
            dataset, // data
            true, // include legend
            true, false);//from  w  ww. j a  v a  2s .c  o  m
    chart.setBackgroundPaint(null);
    //chart.setBorderStroke(null);
    chart.setBorderVisible(false);
    final PiePlot plot = (PiePlot) chart.getPlot();
    // plot.setBackgroundPaint(null);
    //  plot.setShadowPaint(null);

    for (Object o : marks.keySet()) {
        if (iCurrentView == ID_ALLY_CHART) {
            Ally a = (Ally) o;
            plot.setSectionPaint(a.getTag(), marks.get(a).getMarkerColor());
        } else {
            Tribe t = (Tribe) o;
            plot.setSectionPaint(t.getName(), marks.get(t).getMarkerColor());
        }
    }
    //plot.setCircular(true);
    //  plot.setMaximumLabelWidth(30.0);
    /*
        * plot.setLabelGenerator(new StandardPieSectionLabelGenerator( "{0} = {2}", NumberFormat.getNumberInstance(),
        * NumberFormat.getPercentInstance()));
        */
    //   chart.getLegend().setVerticalAlignment(VerticalAlignment.CENTER);
    //  chart.getLegend().setPosition(RectangleEdge.RIGHT);
    // plot.setMaximumLabelWidth(20.0);
    plot.setLabelGenerator(null);
    plot.setBackgroundPaint(Constants.DS_BACK);
    /*
     * plot.setInteriorGap(0.0); plot.setLabelGap(0.0);
     */
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0} = {2}",
            NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));

    /*
     * plot.getL plot.setLabelFont(g2d.getFont().deriveFont(10.0f));
     */

    //plot.setLabelGenerator(null);

    //plot.setMaximumLabelWidth(30.0);
    //plot.getLabelDistributor().distributeLabels(10.0, 20.0);
    //chart.draw(g2d, new Rectangle2D.Float(20, 20, 100, 100));

    //  g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
    plot.setOutlineVisible(false);
    mChartImage = chart.createBufferedImage(getWidth(), getHeight());
    //chart.draw(g2d, new Rectangle2D.Float(50, 50, 400, 400));
    //g2d.drawImage(bi, 30, 30, null);

    //  g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

    //bi = chart.createBufferedImage(240, 240);
    // g2d.drawImage(bi, 30, 30, null);
}

From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java

private byte[] generateLayeredBarChart(CategoryDataset dataset, int width, int height) {
    JFreeChart chart = ChartFactory.createBarChart(null, // chart title
            null, // domain axis label
            null, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // the plot orientation
            true, // legend
            true, // tooltips
            false // urls
    );//from   w w w  .  j a  va2  s .  c o  m

    // set background
    chart.setBackgroundPaint(parseColor(statsManager.getChartBackgroundColor()));

    // set chart border
    chart.setPadding(new RectangleInsets(10, 5, 5, 5));
    chart.setBorderVisible(true);
    chart.setBorderPaint(parseColor("#cccccc"));

    // set anti alias
    chart.setAntiAlias(true);

    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    // disable bar outlines...
    LayeredBarRenderer renderer = new LayeredBarRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setSeriesBarWidth(0, .6);
    renderer.setSeriesBarWidth(1, .8);
    renderer.setSeriesBarWidth(2, 1.0);
    plot.setRenderer(renderer);

    // for this renderer, we need to draw the first series last...
    plot.setRowRenderingOrder(SortOrder.DESCENDING);

    // set up gradient paints for series...
    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);

    CategoryAxis domainAxis = (CategoryAxis) plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);

    BufferedImage img = chart.createBufferedImage(width, height);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        log.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java

private byte[] generateLineChart(String siteId, CategoryDataset dataset, int width, int height,
        boolean render3d, float transparency, boolean itemLabelsVisible, boolean smallFontInDomainAxis) {
    JFreeChart chart = null;
    if (render3d)
        chart = ChartFactory.createLineChart3D(null, null, null, dataset, PlotOrientation.VERTICAL, true, false,
                false);/*w ww.  j  av  a 2 s  .  com*/
    else
        chart = ChartFactory.createLineChart(null, null, null, dataset, PlotOrientation.VERTICAL, true, false,
                false);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    // set transparency
    plot.setForegroundAlpha(transparency);

    // set background
    chart.setBackgroundPaint(parseColor(M_sm.getChartBackgroundColor()));

    // set chart border
    chart.setPadding(new RectangleInsets(10, 5, 5, 5));
    chart.setBorderVisible(true);
    chart.setBorderPaint(parseColor("#cccccc"));

    // set antialias
    chart.setAntiAlias(true);

    // set domain axis font size
    if (smallFontInDomainAxis && !canUseNormalFontSize(width)) {
        plot.getDomainAxis().setTickLabelFont(new Font("SansSerif", Font.PLAIN, 8));
        plot.getDomainAxis().setCategoryMargin(0.05);
    }

    // set outline
    LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
    renderer.setDrawOutlines(true);

    // item labels
    if (itemLabelsVisible) {
        plot.getRangeAxis().setUpperMargin(0.2);
        renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator() {
            private static final long serialVersionUID = 1L;

            @Override
            public String generateLabel(CategoryDataset dataset, int row, int column) {
                Number n = dataset.getValue(row, column);
                if (n.intValue() != 0)
                    //return n.intValue()+"";
                    return n.toString();
                return "";
            }
        });
        renderer.setItemLabelFont(new Font("SansSerif", Font.PLAIN, 8));
        renderer.setItemLabelsVisible(true);
    }

    BufferedImage img = chart.createBufferedImage(width, height);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        LOG.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java

private byte[] createToolAnalysisChart(int width, int height) {
    CategoryDataset dataset = getToolAnalysisDataSet();

    if (dataset == null) {
        return generateNoDataChart(width, height);
    }/* w w w  .ja  v a2s  .co  m*/

    JFreeChart chart = ChartFactory.createBarChart(null, // chart title
            null, // domain axis label
            null, // range axis label
            dataset, // data
            PlotOrientation.HORIZONTAL, // the plot orientation
            false, // legend
            false, // tooltips
            false // urls
    );

    // set background
    chart.setBackgroundPaint(parseColor(statsManager.getChartBackgroundColor()));

    // set chart border
    chart.setPadding(new RectangleInsets(10, 5, 5, 5));
    chart.setBorderVisible(true);
    chart.setBorderPaint(parseColor("#cccccc"));

    // set anti alias
    chart.setAntiAlias(true);

    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    // set transparency
    plot.setForegroundAlpha(0.7f);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinesVisible(false);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setVisible(false);
    domainAxis.setUpperMargin(0);
    domainAxis.setLowerMargin(0);

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setUpperMargin(0.20);
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    CategoryItemLabelGenerator generator = new StandardCategoryItemLabelGenerator("{1}",
            NumberFormat.getInstance(new ResourceLoader().getLocale()));
    renderer.setBaseItemLabelGenerator(generator);
    renderer.setBaseItemLabelFont(new Font("SansSerif", Font.PLAIN, 9));
    renderer.setBaseItemLabelsVisible(true);
    renderer.setItemMargin(0);
    renderer.setSeriesPaint(0, Color.BLUE);

    BufferedImage img = chart.createBufferedImage(width, height);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        log.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java

private byte[] generateStackedAreaChart(CategoryDataset dataset, int width, int height) {
    JFreeChart chart = ChartFactory.createStackedAreaChart(null, // chart title
            null, // domain axis label
            null, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // the plot orientation
            true, // legend
            true, // tooltips
            false // urls
    );/* w  ww .j a v a 2 s.  co  m*/

    // set background
    chart.setBackgroundPaint(parseColor(statsManager.getChartBackgroundColor()));

    // set chart border
    chart.setPadding(new RectangleInsets(10, 5, 5, 5));
    chart.setBorderVisible(true);
    chart.setBorderPaint(parseColor("#cccccc"));

    // set anti alias
    chart.setAntiAlias(true);

    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    // set transparency
    plot.setForegroundAlpha(0.7f);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    // set colour of regular users using Karate belt colour: white, green, blue, brown, black/gold
    CategoryItemRenderer renderer = plot.getRenderer();
    renderer.setSeriesPaint(0, new Color(205, 173, 0)); // gold users
    renderer.setSeriesPaint(1, new Color(139, 69, 19));
    renderer.setSeriesPaint(2, Color.BLUE);
    renderer.setSeriesPaint(3, Color.GREEN);
    renderer.setSeriesPaint(4, Color.WHITE);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    CategoryAxis domainAxis = (CategoryAxis) plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);

    BufferedImage img = chart.createBufferedImage(width, height);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        log.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:skoa.helpers.Graficos.java

private void barrasDual2() {
    unificarDatosFicheros();/*from w  w w .j av  a  2  s .com*/
    Vector<String> vectorOrdenUnidades = new Vector<String>();
    vectorOrdenUnidades = ordenDeUnidades();
    aplicarDiferencia(vectorOrdenUnidades);
    //En este caso, que queremos 2 ejes, MARCAMOS LA DIFERENCIA AL RECOGER EL 2 DATASET.
    CategoryDataset dataset = obtenerSerieBarrasDual(1);
    //String unidad=vectorOrdenUnidades.elementAt(0);
    String unidad;
    if (vectorOrdenUnidades.elementAt(0).indexOf("W") >= 0 || vectorOrdenUnidades.elementAt(0).indexOf("L") >= 0
            || vectorOrdenUnidades.elementAt(0).indexOf("m") >= 0
            || vectorOrdenUnidades.elementAt(0).indexOf("B") >= 0)
        unidad = vectorOrdenUnidades.elementAt(0);
    else if (vectorOrdenUnidades.elementAt(0).indexOf("C") >= 0)
        unidad = "C";
    else
        unidad = "";
    final CategoryAxis domainAxis = new CategoryAxis("Fechas");
    final NumberAxis rangeAxis = new NumberAxis("Mediciones (" + unidad + ")");
    final BarRenderer renderer1 = new BarRenderer();
    final CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer1) {
        private static final long serialVersionUID = 1L;

        //ESPECIAL. Modificamos la leyenda, para que se vea correcta, cogiendo los 2 items deseados.
        public LegendItemCollection getLegendItems() {
            final LegendItemCollection result = new LegendItemCollection();
            final CategoryDataset data = getDataset();
            if (data != null) {
                final CategoryItemRenderer r = getRenderer();
                if (r != null) {
                    final LegendItem item;
                    try { //Se recoge la excepcion en caso de haber solo
                        item = r.getLegendItem(0, 0); //una lnea en el fichero unificado, porque
                    } catch (Exception e) { //no habria nada en diferenciaAplicada.
                        System.out.println("MAL " + e);
                        return null;
                    }
                    result.add(item);
                }
            }
            final CategoryDataset dset2 = getDataset(1);
            if (dset2 != null) {
                final CategoryItemRenderer renderer2 = getRenderer(1);
                if (renderer2 != null) {
                    final LegendItem item = renderer2.getLegendItem(1, 1);
                    result.add(item);
                }
            }
            return result;
        }
    };
    final JFreeChart grafica = new JFreeChart("Valores medidos de las direcciones de grupo", plot);
    plot.setBackgroundPaint(new Color(0xEE, 0xEE, 0xFF));
    plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    CategoryDataset dataset2 = obtenerSerieBarrasDual(2);
    //unidad=vectorOrdenUnidades.elementAt(1);
    if (vectorOrdenUnidades.elementAt(1).indexOf("W") >= 0 || vectorOrdenUnidades.elementAt(1).indexOf("L") >= 0
            || vectorOrdenUnidades.elementAt(1).indexOf("m") >= 0
            || vectorOrdenUnidades.elementAt(1).indexOf("B") >= 0)
        unidad = vectorOrdenUnidades.elementAt(1);
    else if (vectorOrdenUnidades.elementAt(1).indexOf("C") >= 0)
        unidad = "C";
    else
        unidad = "";
    plot.setDataset(1, dataset2);
    plot.mapDatasetToRangeAxis(1, 1);
    final ValueAxis axis2 = new NumberAxis("Mediciones (" + unidad + ")");
    plot.setRangeAxis(1, axis2);
    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
    final BarRenderer renderer2 = new BarRenderer();
    renderer2.setShadowVisible(false); //Esconder las sombras de la barra 1.
    plot.setRenderer(1, renderer2);
    BarRenderer renderer = new BarRenderer();
    renderer.setShadowVisible(false); //Esconder las sombras de la barra 2.
    plot.setRenderer(0, renderer);
    plot.setRangeGridlinePaint(Color.BLACK); //Color de las lineas divisorias.
    //Subttulos
    if (fechaInicial.isEmpty()) {
        fechaInicial = fechaFinal = "?";
    }
    TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal,
            new Font("SanSerif", Font.ITALIC, 12));
    grafica.addSubtitle(t);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    domainAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 8)); //Letra de las fechas ms pequea
    grafica.setBackgroundPaint(Color.white);
    //-------------------------------------------------
    //Guarda la imagen:
    BufferedImage i1 = grafica.createBufferedImage(400, 300);
    BufferedImage i2 = grafica.createBufferedImage(900, 600);
    BufferedImage imag1 = convertirTipo(i1, BufferedImage.TYPE_INT_RGB);//!OBLIGATORIO!Para que al guardar la imagen,
    BufferedImage imag2 = convertirTipo(i2, BufferedImage.TYPE_INT_RGB);//no se vea transparente naranja.
    try {
        ImageIO.write(imag1, "jpg", new File(ruta + "BarrasSmall.jpg"));
        ImageIO.write(imag2, "jpg", new File(ruta + "BarrasBig.jpg"));
    } catch (IOException e) {
        System.out.println("Error de escritura");
    }
}