Example usage for org.jfree.chart JFreeChart draw

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

Introduction

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

Prototype

@Override
public void draw(Graphics2D g2, Rectangle2D area) 

Source Link

Document

Draws the chart on a Java 2D graphics device (such as the screen or a printer).

Usage

From source file:net.sf.jasperreports.charts.util.ImageChartRendererFactory.java

@Override
public Renderable getRenderable(JasperReportsContext jasperReportsContext, JFreeChart chart,
        ChartHyperlinkProvider chartHyperlinkProvider, Rectangle2D rectangle) {
    int dpi = JRPropertiesUtil.getInstance(jasperReportsContext)
            .getIntegerProperty(Renderable.PROPERTY_IMAGE_DPI, 72);
    double scale = dpi / 72d;

    BufferedImage bi = new BufferedImage((int) (scale * (int) rectangle.getWidth()),
            (int) (scale * rectangle.getHeight()), BufferedImage.TYPE_INT_ARGB);

    List<JRPrintImageAreaHyperlink> areaHyperlinks = null;

    Graphics2D grx = bi.createGraphics();
    try {/*from  www  .  j av a  2s. c  om*/
        grx.scale(scale, scale);

        if (chartHyperlinkProvider != null && chartHyperlinkProvider.hasHyperlinks()) {
            areaHyperlinks = ChartUtil.getImageAreaHyperlinks(chart, chartHyperlinkProvider, grx, rectangle);
        } else {
            chart.draw(grx, rectangle);
        }
    } finally {
        grx.dispose();
    }

    try {
        return new SimpleDataRenderer(
                JRImageLoader.getInstance(jasperReportsContext).loadBytesFromAwtImage(bi, ImageTypeEnum.PNG),
                areaHyperlinks);
    } catch (JRException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:keel.Algorithms.UnsupervisedLearning.AssociationRules.Visualization.keelassotiationrulesboxplot.ResultsProccessor.java

public void writeToFile(String outName)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    //calcMeans();

    // Create JFreeChart Dataset
    DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

    HashMap<String, ArrayList<Double>> measuresFirst = algorithmMeasures.entrySet().iterator().next()
            .getValue();/*from   www.j  a va 2  s.  c  om*/
    for (Map.Entry<String, ArrayList<Double>> measure : measuresFirst.entrySet()) {
        String measureName = measure.getKey();
        //Double measureValue = measure.getValue();
        dataset.clear();

        for (Map.Entry<String, HashMap<String, ArrayList<Double>>> entry : algorithmMeasures.entrySet()) {
            String alg = entry.getKey();
            ArrayList<Double> measureValues = entry.getValue().get(measureName);

            // Parse algorithm name to show it correctly
            String aName = alg.substring(0, alg.length() - 1);
            int startAlgName = aName.lastIndexOf("/");
            aName = aName.substring(startAlgName + 1);

            dataset.add(measureValues, aName, measureName);
        }

        // Tutorial: http://www.java2s.com/Code/Java/Chart/JFreeChartBoxAndWhiskerDemo.htm
        final CategoryAxis xAxis = new CategoryAxis("Algorithm");
        final NumberAxis yAxis = new NumberAxis("Value");
        yAxis.setAutoRangeIncludesZero(false);
        final BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();

        // Black and White
        int numItems = algorithmMeasures.size();
        for (int i = 0; i < numItems; i++) {
            Color color = Color.DARK_GRAY;
            if (i % 2 == 1) {
                color = Color.LIGHT_GRAY;
            }
            renderer.setSeriesPaint(i, color);
            renderer.setSeriesOutlinePaint(i, Color.BLACK);
        }

        renderer.setMeanVisible(false);
        renderer.setFillBox(false);
        renderer.setToolTipGenerator(new BoxAndWhiskerToolTipGenerator());
        final CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis, renderer);

        Font font = new Font("SansSerif", Font.BOLD, 10);
        //ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
        JFreeChart jchart = new JFreeChart("Assotiation Rules Measures - BoxPlot", font, plot, true);
        //StandardChartTheme.createLegacyTheme().apply(jchart);

        int width = 640 * 2; /* Width of the image */
        int height = 480 * 2; /* Height of the image */

        // JPEG
        File chart = new File(outName + "_" + measureName + "_boxplot.jpg");
        ChartUtilities.saveChartAsJPEG(chart, jchart, width, height);

        // SVG
        SVGGraphics2D g2 = new SVGGraphics2D(width, height);
        Rectangle r = new Rectangle(0, 0, width, height);
        jchart.draw(g2, r);
        File BarChartSVG = new File(outName + "_" + measureName + "_boxplot.svg");
        SVGUtils.writeToSVG(BarChartSVG, g2.getSVGElement());
    }

}

From source file:com.rapidminer.gui.plotter.charts.AbstractBarChartPlotter.java

public void paintBarChart(Graphics graphics) {
    int categoryCount = prepareData();
    String groupByName = groupByColumn >= 0 ? dataTable.getColumnName(groupByColumn) : null;
    String valueName = valueColumn >= 0 ? dataTable.getColumnName(valueColumn) : null;
    String maxClassesProperty = System.getProperty(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_COLORS_CLASSLIMIT);
    int maxClasses = 20;
    try {// www .  ja  v  a2  s  . c  om
        if (maxClassesProperty != null)
            maxClasses = Integer.parseInt(maxClassesProperty);
    } catch (NumberFormatException e) {
        LogService.getGlobal().log(
                "Bar Chart plotter: cannot parse property 'rapidminer.gui.plotter.colors.classlimit', using maximal 20 different classes.",
                LogService.WARNING);
    }
    boolean createLegend = categoryCount > 0 && categoryCount < maxClasses;

    if (categoryCount <= MAX_CATEGORIES) {
        JFreeChart chart = createChart(categoryDataSet, groupByName, valueName, createLegend);

        // set the background color for the chart...
        chart.setBackgroundPaint(Color.white);

        // legend settings
        LegendTitle legend = chart.getLegend();
        if (legend != null) {
            legend.setPosition(RectangleEdge.TOP);
            legend.setFrame(BlockBorder.NONE);
            legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
        }

        Rectangle2D drawRect = new Rectangle2D.Double(0, 0, getWidth(), getHeight());
        chart.draw((Graphics2D) graphics, drawRect);
    } else {
        graphics.drawString("Too many columns (" + categoryCount + "), this chart is only able to plot up to "
                + MAX_CATEGORIES + " different categories", MARGIN, MARGIN);
    }
}

From source file:com.xpn.xwiki.plugin.charts.ChartingPlugin.java

private Chart generateSvgChart(JFreeChart jfchart, ChartParams params, XWikiContext context)
        throws IOException, GenerateException {
    // Get a DOMImplementation
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    // Create an instance of org.w3c.dom.Document
    Document document = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null);
    // Create an instance of the SVG Generator
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
    // Ask the chart to render into the SVG Graphics2D implementation
    Rectangle2D.Double rect = new Rectangle2D.Double(0, 0, params.getInteger(ChartParams.WIDTH).intValue(),
            params.getInteger(ChartParams.HEIGHT).intValue());
    jfchart.draw(svgGenerator, rect);
    boolean useCSS = false;
    StringWriter swriter = new StringWriter();
    svgGenerator.stream(swriter, useCSS);
    String svgText = swriter.toString();

    String pageURL = null;/*from w w  w  . j  ava2  s.c o m*/
    SVGPlugin svgPlugin = (SVGPlugin) context.getWiki().getPlugin("svg", context);
    if (svgPlugin == null) {
        throw new GenerateException("SVGPlugin not loaded");
    }

    String imageURL;
    try {
        imageURL = svgPlugin.getSVGImageURL(svgText, params.getInteger(ChartParams.HEIGHT).intValue(),
                params.getInteger(ChartParams.WIDTH).intValue(), context);
    } catch (SVGConverterException sce) {
        throw new GenerateException(sce);
    }

    return new ChartImpl(params, imageURL, pageURL);
}

From source file:org.sakaiproject.evaluation.tool.reporting.EvalPDFReportBuilder.java

/**
  * @param question/*from   w  ww.ja v a2  s . com*/
  *            the question text
  * @param choices
  *            the text for the choices
  * @param values
  *            the count of answers for each choice (same order as choices)
  * @param responseCount
  *            the number of responses to the question
  * @param showPercentages
  *            if true then show the percentages
  * @param answersAndMean
  *            the text which will be displayed above the chart (normally the answers count and
  *            mean)
  * @param lastElementIsHeader
  *            If the last element was a header, the extra spacing paragraph is not needed.
  */
public void addLikertResponse(String question, String[] choices, int[] values, int responseCount,
        boolean showPercentages, String answersAndMean, boolean lastElementIsHeader) {
    ArrayList<Element> myElements = new ArrayList<>();

    try {
        if (!lastElementIsHeader) {
            Paragraph emptyPara = new Paragraph(" ");
            this.addElementWithJump(emptyPara, false);
        }

        Paragraph myPara = new Paragraph(question, questionTextFont);
        myPara.setSpacingAfter(SPACING_AFTER_HEADER);
        myElements.add(myPara);

        EvalLikertChartBuilder chartBuilder = new EvalLikertChartBuilder();
        chartBuilder.setValues(values);
        chartBuilder.setResponses(choices);
        chartBuilder.setShowPercentages(showPercentages);
        chartBuilder.setResponseCount(responseCount);
        JFreeChart chart = chartBuilder.makeLikertChart();

        /* The height is going to be based off the number of choices */
        int height = 15 * choices.length;

        PdfContentByte cb = pdfWriter.getDirectContent();
        PdfTemplate tp = cb.createTemplate(200, height);
        Graphics2D g2d = tp.createGraphics(200, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, 200, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        Image image = Image.getInstance(tp);

        // put image in the document
        myElements.add(image);

        if (answersAndMean != null) {
            Paragraph header = new Paragraph(answersAndMean, paragraphFont);
            header.setSpacingAfter(SPACING_BETWEEN_LIST_ITEMS);
            myElements.add(header);
        }

        this.addElementArrayWithJump(myElements);
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        LOG.warn(e);
    }
}

From source file:com.rapidminer.gui.plotter.DistributionPlotter.java

public void paintComponent(Graphics graphics, int width, int height) {
    preparePlots();// w  w w .  ja v a2 s .  c om
    if (plot) {
        JFreeChart chart = null;
        try {
            if (!Double.isNaN(model.getUpperBound(plotColumn))) {
                chart = createNumericalChart();
            } else {
                chart = createNominalChart();
            }
        } catch (Exception e) {
            // do nothing - just do not draw the chart
        }

        if (chart != null) {
            // set the background color for the chart...
            chart.setBackgroundPaint(Color.white);

            // legend settings
            LegendTitle legend = chart.getLegend();
            if (legend != null) {
                legend.setPosition(RectangleEdge.TOP);
                legend.setFrame(BlockBorder.NONE);
                legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
            }
            Rectangle2D drawRect = new Rectangle2D.Double(0, 0, width, height);
            chart.draw((Graphics2D) graphics, drawRect);
        }
    }
}

From source file:ch.agent.crnickl.demo.stox.Chart.java

private void saveChartAsSVG(JFreeChart chart, String fileName, int width, int height) throws KeyedException {
    Writer out = null;//from  w  w w  .ja v a  2  s  .c o m
    try {
        out = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
        String svgNS = "http://www.w3.org/2000/svg";
        DOMImplementation di = DOMImplementationRegistry.newInstance().getDOMImplementation("XML 1.0");
        Document document = di.createDocument(svgNS, "svg", null);

        SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
        ctx.setEmbeddedFontsOn(true);
        SVGGraphics2D svgGenerator = new CustomSVGGraphics2D(ctx, true, 100, true);
        svgGenerator.setSVGCanvasSize(new Dimension(width, height));
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height));
        boolean useCSS = true;
        svgGenerator.stream(out, useCSS);
        svgGenerator.dispose();
    } catch (Exception e) {
        throw K.JFC_OUTPUT_ERR.exception(e, fileName);
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:de.fau.amos.ChartToPDF.java

/**
 * Converts Chart into PDF/*from   ww  w.j av  a2s .  c  om*/
 * 
 * @param chart JFreeChart from CharRenderer that will be displayed in the PDF file
 * @param fileName Name of created PDF-file
 */
public void convertChart(JFreeChart chart, String fileName) {
    if (chart != null) {

        //set page size
        float width = PageSize.A4.getWidth();
        float height = PageSize.A4.getHeight();

        //creating a new pdf document
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer;
        try {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(new File(System.getProperty("userdir.location"), fileName + ".pdf")));
        } catch (DocumentException e) {
            e.printStackTrace();
            return;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }

        document.addAuthor("Green Energy Cockpit");
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);

        //sets the pdf page
        Graphics2D g2D = new PdfGraphics2D(tp, width, height);
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);

        //draws the passed JFreeChart into the PDF file
        chart.draw(g2D, r2D);

        g2D.dispose();
        cb.addTemplate(tp, 0, 0);

        document.close();

        writer.flush();
        writer.close();
    }
}

From source file:SciTK.Plot.java

/**
 * Exports a JFreeChart to a SVG file using Apache Batik library.
 * /*from   w  ww  .j  a  va 2 s. c  om*/
 * @param chart JFreeChart to export
 * @param bounds the dimensions of the viewport
 * @param svgFile the output file.
 * @throws IOException if writing the svgFile fails.
 */
protected void exportChartAsSVG(JFreeChart chart, Rectangle bounds, File svgFile) throws IOException {
    // see http://dolf.trieschnigg.nl/jfreechart/

    // Get a DOMImplementation and create an XML document
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument(null, "svg", null);

    // Create an instance of the SVG Generator
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    // draw the chart in the SVG generator
    chart.draw(svgGenerator, bounds);

    // Write svg file
    OutputStream outputStream = new FileOutputStream(svgFile);
    Writer out = new OutputStreamWriter(outputStream, "UTF-8");
    svgGenerator.stream(out, true /* use css */);

    // write and close file:                   
    outputStream.flush();
    outputStream.close();
}

From source file:de.iteratec.iteraplan.presentation.dialog.GraphicalReporting.Line.JFreeChartSvgRenderer.java

byte[] renderJFreeChart(JFreeChart chart, float width, float height, boolean naked, Date fromDate, Date toDate)
        throws IOException {
    String svgNamespaceUri = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document doc = SVGDOMImplementation.getDOMImplementation().createDocument(svgNamespaceUri, "svg", null);

    String generatedText = "Generated "
            + DateUtils.formatAsStringToLong(new Date(), UserContext.getCurrentLocale()) + " by "
            + MessageAccess.getStringOrNull("global.applicationname", UserContext.getCurrentLocale()) + " "
            + properties.getBuildId();/*from  w  w  w. j  a v  a  2  s .c o m*/
    String drawingInfo = MessageAccess.getStringOrNull("graphicalExport.timeline.drawInfo",
            UserContext.getCurrentLocale()) + ": "
            + DateUtils.formatAsString(fromDate, UserContext.getCurrentLocale()) + " -> "
            + DateUtils.formatAsString(toDate, UserContext.getCurrentLocale());

    SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(doc);
    ctx.setComment(generatedText);
    SVGGraphics2D svgGraphics = new SVGGraphics2D(ctx, false);

    if (!naked) {
        //Render the chart to the SVG graphics object
        chart.draw(svgGraphics, new Rectangle(20, 20, Math.round(width - MARGIN), Math.round(height - MARGIN)));

        //Add logo and generated text
        int widthIntForLogo = Math.round(width + 40 - MARGIN);
        int heightIntForLogo = Math.round(height - MARGIN + 20);

        int xLogoUpperRightCorner[] = { widthIntForLogo - 40, widthIntForLogo, widthIntForLogo,
                widthIntForLogo - 8, widthIntForLogo - 8, widthIntForLogo - 40 };
        int yLogoUpperRightCorner[] = { MARGIN_TOP, MARGIN_TOP, MARGIN_TOP + 40, MARGIN_TOP + 40,
                MARGIN_TOP + 8, MARGIN_TOP + 8 };

        GeneralPath logoUpperRightCorner = new GeneralPath();
        logoUpperRightCorner.moveTo(xLogoUpperRightCorner[0], yLogoUpperRightCorner[0]);
        for (int i = 1; i < xLogoUpperRightCorner.length; i++) {
            logoUpperRightCorner.lineTo(xLogoUpperRightCorner[i], yLogoUpperRightCorner[i]);
        }
        logoUpperRightCorner.closePath();
        svgGraphics.setColor(Color.decode(COLOR_LOGO));
        svgGraphics.fill(logoUpperRightCorner);
        svgGraphics.draw(logoUpperRightCorner);

        int xLogoLowerLeftCorner[] = { MARGIN_LEFT, MARGIN_LEFT + 8, MARGIN_LEFT + 8, MARGIN_LEFT + 40,
                MARGIN_LEFT + 40, MARGIN_LEFT };
        int yLogoLowerLeftCorner[] = { heightIntForLogo, heightIntForLogo, heightIntForLogo + 32,
                heightIntForLogo + 32, heightIntForLogo + 40, heightIntForLogo + 40 };

        GeneralPath logoLowerLeftCorner = new GeneralPath();
        logoLowerLeftCorner.moveTo(xLogoLowerLeftCorner[0], yLogoLowerLeftCorner[0]);
        for (int i = 1; i < xLogoLowerLeftCorner.length; i++) {
            logoLowerLeftCorner.lineTo(xLogoLowerLeftCorner[i], yLogoLowerLeftCorner[i]);
        }
        logoLowerLeftCorner.closePath();
        svgGraphics.setColor(Color.BLACK);
        svgGraphics.fill(logoLowerLeftCorner);
        svgGraphics.draw(logoLowerLeftCorner);

        Font f = new Font(null, Font.ITALIC, 12);
        svgGraphics.setFont(f);
        FontMetrics fontMetrics = svgGraphics.getFontMetrics(f);
        int charsWidthInfo = fontMetrics.stringWidth(drawingInfo);
        svgGraphics.drawString(drawingInfo, width - MARGIN - charsWidthInfo,
                height - MARGIN + MARGIN_DOWN_GENERATED_TEXT);
        int charsWidth = fontMetrics.stringWidth(generatedText);
        svgGraphics.drawString(generatedText, width - MARGIN - charsWidth,
                height - MARGIN + MARGIN_DOWN_GENERATED_TEXT + 20);

    } else {
        chart.draw(svgGraphics,
                new Rectangle(20, 20, Math.round(JFreeChartLineGraphicCreator.DEFAULT_HEIGHT - NAKED_MARGIN),
                        Math.round(JFreeChartLineGraphicCreator.DEFAULT_HEIGHT - NAKED_MARGIN)));
    }

    svgGraphics.setSVGCanvasSize(new Dimension((int) width, (int) height));

    //Convert the SVGGraphics2D object to SVG XML 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer out = new OutputStreamWriter(baos, "UTF-8");
    svgGraphics.stream(out, true);
    byte[] originalSvgXml = baos.toByteArray();

    //    return originalSvgXml;
    return addAdditionalAttributes(originalSvgXml);
}