Example usage for org.jfree.chart ChartUtilities writeChartAsPNG

List of usage examples for org.jfree.chart ChartUtilities writeChartAsPNG

Introduction

In this page you can find the example usage for org.jfree.chart ChartUtilities writeChartAsPNG.

Prototype

public static void writeChartAsPNG(OutputStream out, JFreeChart chart, int width, int height)
        throws IOException 

Source Link

Document

Writes a chart to an output stream in PNG format.

Usage

From source file:se.technipelago.weather.chart.Generator.java

public void createHistoryChart(final Timespan period, final String column, final String title,
        final String legend, final OutputStream out, final int width, final int height) throws IOException {
    try {//  ww  w .j a  va2s .  com
        log.fine("Period from " + period.getStartTime().toString() + " to " + period.getEndTime().toString());
        XYDataset dataset = createHistoryDataset(period.getStartTime(), period.getEndTime(), column, title);
        JFreeChart chart = createLineChart(title + " " + period, legend, dataset);
        chart.setBackgroundPaint(VERY_LIGHT_GRAY);
        ChartUtilities.writeChartAsPNG(out, chart, width, height);
    } catch (SQLException e) {
        log.log(Level.SEVERE, "SQL Error", e);
    }
}

From source file:se.technipelago.weather.chart.Generator.java

public void createRainHistoryChart(final Timespan period, final OutputStream out, final int width,
        final int height) throws IOException {
    try {//  w  w w  .  java  2 s  .  c o m
        log.fine("Period from " + period.getStartTime().toString() + " to " + period.getEndTime().toString());
        CategoryDataset dataset = createRainDataset(period.getStartTime(), period.getEndTime());
        JFreeChart chart = createBarChart("Nederb\u00f6rd " + period, "millimeter", dataset);
        chart.setBackgroundPaint(VERY_LIGHT_GRAY);
        ChartUtilities.writeChartAsPNG(out, chart, width, height);
    } catch (SQLException e) {
        log.log(Level.SEVERE, "SQL Error", e);
    }
}

From source file:se.technipelago.weather.chart.Generator.java

private void createTemperatureDial(float temperature, int humidity, final String filename) throws IOException {
    ValueDataset dataset1 = new DefaultValueDataset(temperature);
    ValueDataset dataset2 = new DefaultValueDataset(humidity);

    // get data for diagrams
    DialPlot plot = new DialPlot();
    plot.setView(0.0, 0.0, 1.0, 1.0);/*from   ww  w . j ava 2s .c  om*/
    plot.setDataset(0, dataset1);
    plot.setDataset(1, dataset2);
    StandardDialFrame dialFrame = new StandardDialFrame();
    dialFrame.setBackgroundPaint(Color.lightGray);
    dialFrame.setForegroundPaint(Color.darkGray);
    plot.setDialFrame(dialFrame);

    GradientPaint gp = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 220));
    DialBackground db = new DialBackground(gp);
    db.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
    plot.setBackground(db);

    // Temperature
    DialTextAnnotation annotation1 = new DialTextAnnotation("\u00B0C");
    annotation1.setFont(new Font("Dialog", Font.BOLD, 10));
    annotation1.setRadius(0.76);

    plot.addLayer(annotation1);

    // Humidity
    DialTextAnnotation annotation2 = new DialTextAnnotation("%");
    annotation2.setFont(new Font("Dialog", Font.BOLD, 10));
    annotation2.setPaint(Color.blue);
    annotation2.setRadius(0.4);

    plot.addLayer(annotation2);

    // Temperature
    DialValueIndicator dvi = new DialValueIndicator(0);
    dvi.setFont(new Font("Dialog", Font.PLAIN, 9));
    dvi.setOutlinePaint(Color.darkGray);
    //dvi.setBackgroundPaint(new Color(0xee, 0xee, 0xf6));
    NumberFormat fmt = new DecimalFormat("#");
    fmt.setMaximumFractionDigits(1);
    fmt.setMinimumIntegerDigits(1);
    dvi.setNumberFormat(fmt);
    dvi.setRadius(0.71);
    dvi.setAngle(-88.0); // -103
    dvi.setInsets(new RectangleInsets(0.0, 8.0, 0.0, 2.0)); // top, left, bottom, right
    plot.addLayer(dvi);

    StandardDialScale scale = new StandardDialScale(-30, 30, -120, -300, 5, 4);
    scale.setTickRadius(0.88);
    scale.setTickLabelOffset(0.15);
    scale.setTickLabelFont(new Font("Dialog", Font.PLAIN, 10));
    NumberFormat fmt3 = new DecimalFormat("#");
    fmt3.setMaximumFractionDigits(0);
    scale.setTickLabelFormatter(fmt3);
    plot.addScale(0, scale);

    // Humidity
    DialValueIndicator dvi2 = new DialValueIndicator(1);
    dvi2.setFont(new Font("Dialog", Font.PLAIN, 9));
    dvi2.setOutlinePaint(Color.blue);
    //dvi2.setBackgroundPaint(new Color(0xee, 0xee, 0xf6));
    NumberFormat fmt2 = new DecimalFormat("#");
    fmt2.setMaximumFractionDigits(0);
    dvi2.setNumberFormat(fmt2);

    dvi2.setRadius(0.59);
    dvi2.setAngle(-90.0); // -77
    dvi2.setInsets(new RectangleInsets(0.0, 1.0, 0.0, 1.0));
    plot.addLayer(dvi2);

    StandardDialScale scale2 = new StandardDialScale(0, 100, -120, -300, 10, 4);
    scale2.setTickRadius(0.50);
    scale2.setTickLabelOffset(0.15);
    scale2.setTickLabelFont(new Font("Dialog", Font.PLAIN, 9));
    scale2.setTickLabelFormatter(fmt3);
    scale2.setMajorTickPaint(Color.blue);
    plot.addScale(1, scale2);
    plot.mapDatasetToScale(1, 1);

    // Add needles.
    // To make the temperature needle the front-most needle,
    // it must be added after humidity needle.
    // Humidity needle.
    DialPointer needle2 = new DialPointer.Pin(1);
    needle2.setRadius(0.50);
    plot.addLayer(needle2);

    // Temperature needle.
    DialPointer needle = new DialPointer.Pointer(0);
    Color darkGreen = new Color(0x15, 0x49, 0x1f);
    ((DialPointer.Pointer) needle).setFillPaint(darkGreen);
    plot.addLayer(needle);

    // Add a cap at the dial center.
    DialCap cap = new DialCap();
    cap.setRadius(0.10);
    plot.setCap(cap);

    JFreeChart chart = new JFreeChart(plot);
    //TextTitle title = new TextTitle("Temperatur/luftfuktighet", new Font("Dialog", Font.BOLD, 12));
    //title.setPaint(Color.DARK_GRAY);
    //chart.setTitle(title);
    chart.setBackgroundPaint(VERY_LIGHT_GRAY);

    OutputStream out = null;
    try {
        out = new FileOutputStream(outputDir != null ? outputDir + "/" + filename : filename);
        ChartUtilities.writeChartAsPNG(out, chart, DIAL_WIDTH, DIAL_HEIGHT);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

/**
 * @param os response output stream/*www.j  a  v a2  s  .  com*/
 * @param mvr MeanVarianceRelation object to plot
 * @return true if mvr data points were plotted
 */
private boolean writeMeanVariance(OutputStream os, MeanVarianceRelation mvr, Double size) throws Exception {
    // if number of datapoints > THRESHOLD then alpha = TRANSLUCENT, else alpha = OPAQUE
    final int THRESHOLD = 1000;
    final int TRANSLUCENT = 50;
    final int OPAQUE = 255;

    // Set maximum plot range to Y_MAX + YRANGE * OFFSET to leave some extra white space
    final double OFFSET_FACTOR = 0.05f;

    // set the final image size to be the minimum of MAX_IMAGE_SIZE_PX or size
    final int MAX_IMAGE_SIZE_PX = 5;

    if (mvr == null) {
        return false;
    }

    // get data points
    XYSeriesCollection collection = this.getMeanVariance(mvr);

    if (collection.getSeries().size() == 0) {
        return false;
    }

    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    JFreeChart chart = ChartFactory.createScatterPlot("", "mean (log2)", "variance (log2)", collection,
            PlotOrientation.VERTICAL, false, false, false);

    // adjust colors and shapes
    XYRegressionRenderer renderer = new XYRegressionRenderer();
    renderer.setBasePaint(Color.white);
    XYSeries series = collection.getSeries(0);
    int alpha = series.getItemCount() > THRESHOLD ? TRANSLUCENT : OPAQUE;
    renderer.setSeriesPaint(0, new Color(0, 0, 0, alpha));
    renderer.setSeriesPaint(1, Color.red);
    renderer.setSeriesStroke(1, new BasicStroke(1));
    renderer.setSeriesShape(0, new Ellipse2D.Double(4, 4, 4, 4));
    renderer.setSeriesShapesFilled(0, false);
    renderer.setSeriesLinesVisible(0, false);
    renderer.setSeriesLinesVisible(1, true);
    renderer.setSeriesShapesVisible(1, false);

    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(renderer);
    plot.setRangeGridlinesVisible(false);
    plot.setDomainGridlinesVisible(false);

    // adjust the chart domain and ranges
    double yRange = series.getMaxY() - series.getMinY();
    double xRange = series.getMaxX() - series.getMinX();
    if (xRange < 0) {
        log.warn("Min X was greater than Max X: Max=" + series.getMaxY() + " Min= " + series.getMinY());
        return false;
    }
    double ybuffer = (yRange) * OFFSET_FACTOR;
    double xbuffer = (xRange) * OFFSET_FACTOR;
    double newYMin = series.getMinY() - ybuffer;
    double newYMax = series.getMaxY() + ybuffer;
    double newXMin = series.getMinX() - xbuffer;
    double newXMax = series.getMaxX() + xbuffer;

    ValueAxis yAxis = new NumberAxis("Variance");
    yAxis.setRange(newYMin, newYMax);
    ValueAxis xAxis = new NumberAxis("Mean");
    xAxis.setRange(newXMin, newXMax);
    chart.getXYPlot().setRangeAxis(yAxis);
    chart.getXYPlot().setDomainAxis(xAxis);

    int finalSize = (int) Math.min(
            MAX_IMAGE_SIZE_PX * ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX,
            size * ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX);

    ChartUtilities.writeChartAsPNG(os, chart, finalSize, finalSize);

    return true;
}

From source file:se.technipelago.weather.chart.Generator.java

private void createWindDial(float speed, float high, final String filename) throws IOException {
    ValueDataset dataset1 = new DefaultValueDataset(speed);
    ValueDataset dataset2 = new DefaultValueDataset(high);

    // get data for diagrams
    DialPlot plot = new DialPlot();
    plot.setView(0.0, 0.0, 1.0, 1.0);//from ww w .ja  v a 2  s.  c o m
    plot.setDataset(0, dataset1);
    plot.setDataset(1, dataset2);
    StandardDialFrame dialFrame = new StandardDialFrame();
    dialFrame.setBackgroundPaint(Color.lightGray);
    dialFrame.setForegroundPaint(Color.darkGray);
    plot.setDialFrame(dialFrame);

    GradientPaint gp = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 220));
    DialBackground db = new DialBackground(gp);
    db.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
    plot.setBackground(db);

    // Wind Speed
    DialTextAnnotation annotation1 = new DialTextAnnotation("m/s");
    annotation1.setFont(new Font("Dialog", Font.BOLD, 10));
    annotation1.setRadius(0.76);

    plot.addLayer(annotation1);

    DialValueIndicator dvi = new DialValueIndicator(0);
    dvi.setFont(new Font("Dialog", Font.PLAIN, 9));
    dvi.setOutlinePaint(Color.darkGray);
    //dvi.setBackgroundPaint(new Color(0xee, 0xee, 0xf6));
    NumberFormat fmt = new DecimalFormat("#");
    fmt.setMaximumFractionDigits(1);
    fmt.setMinimumIntegerDigits(1);
    dvi.setNumberFormat(fmt);
    dvi.setRadius(0.71);
    dvi.setAngle(-89.0); // -103
    dvi.setInsets(new RectangleInsets(0.0, 2.0, 0.0, 2.0)); // top, left, bottom, right
    plot.addLayer(dvi);

    StandardDialScale scale = new StandardDialScale(0, 20, -120, -300, 1, 0);
    scale.setTickRadius(0.88);
    scale.setTickLabelOffset(0.15);
    scale.setTickLabelFont(new Font("Dialog", Font.PLAIN, 10));
    NumberFormat fmt3 = new DecimalFormat("#");
    fmt3.setMaximumFractionDigits(0);
    scale.setTickLabelFormatter(fmt3);
    plot.addScale(0, scale);

    // Add needles.
    // To make the average speed needle the front-most needle,
    // it must be added after high speed needle.
    // High speed needle.
    DialPointer needle2 = new DialPointer.Pin(1);
    needle2.setRadius(0.62);
    plot.addLayer(needle2);

    // Average speed needle.
    DialPointer needle = new DialPointer.Pointer(0);
    Color darkGreen = new Color(0x15, 0x49, 0x1f);
    ((DialPointer.Pointer) needle).setFillPaint(darkGreen);
    plot.addLayer(needle);

    // Add a cap at the dial center.
    DialCap cap = new DialCap();
    cap.setRadius(0.10);
    plot.setCap(cap);

    JFreeChart chart = new JFreeChart(plot);
    //TextTitle title = new TextTitle("Vindhastighet", new Font("Dialog", Font.BOLD, 12));
    //title.setPaint(Color.DARK_GRAY);
    //chart.setTitle(title);
    chart.setBackgroundPaint(VERY_LIGHT_GRAY);

    OutputStream out = null;
    try {
        out = new FileOutputStream(outputDir != null ? outputDir + "/" + filename : filename);
        ChartUtilities.writeChartAsPNG(out, chart, DIAL_WIDTH, DIAL_HEIGHT);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:se.technipelago.weather.chart.Generator.java

private void createWindCompass(int direction, final String filename) throws IOException {
    final ValueDataset dataset = new DefaultValueDataset(direction);
    final CompassPlot plot2 = new CompassPlot(dataset);
    plot2.setSeriesNeedle(7);//from   w w  w  . j  a  va2  s  .  co  m
    plot2.setSeriesPaint(0, Color.red);
    plot2.setSeriesOutlinePaint(0, Color.red);

    final JFreeChart chart = new JFreeChart(plot2);
    //final TextTitle title = new TextTitle("Vindriktning", new Font("Dialog", Font.BOLD, 12));
    //title.setPaint(Color.DARK_GRAY);
    //chart.setTitle(title);
    chart.setBackgroundPaint(VERY_LIGHT_GRAY);

    OutputStream out = null;
    try {
        out = new FileOutputStream(outputDir != null ? outputDir + "/" + filename : filename);
        ChartUtilities.writeChartAsPNG(out, chart, DIAL_WIDTH, DIAL_HEIGHT);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

/**
 * Visualization of the correlation of principal components with factors or the date samples were run.
 *
 * @param svdo SVD value object//from  w  ww .  j  a v a  2 s. com
 */
private void writePCAFactors(OutputStream os, ExpressionExperiment ee, SVDValueObject svdo) throws Exception {
    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());

    if (factorCorrelations.isEmpty() && dateCorrelations.isEmpty()) {
        this.writePlaceholderImage(os);
        return;
    }
    ee = expressionExperimentService.thawLite(ee); // need the experimental design
    int maxWidth = 10;

    Map<Long, String> efs = this.getFactorNames(ee, maxWidth);

    DefaultCategoryDataset series = new DefaultCategoryDataset();

    /*
     * With two groups, or a continuous factor, we get rank correlations
     */
    int MAX_COMP = 3;
    double STUB = 0.05; // always plot a little thing so we know its there.
    for (Integer component : factorCorrelations.keySet()) {
        if (component >= MAX_COMP)
            break;
        for (Long efId : factorCorrelations.get(component).keySet()) {
            Double a = factorCorrelations.get(component).get(efId);
            String facname = efs.get(efId) == null ? "?" : efs.get(efId);
            if (a != null && !Double.isNaN(a)) {
                Double corr = Math.max(STUB, Math.abs(a));
                series.addValue(corr, "PC" + (component + 1), facname);
            }
        }
    }

    for (Integer component : dateCorrelations.keySet()) {
        if (component >= MAX_COMP)
            break;
        Double a = dateCorrelations.get(component);
        if (a != null && !Double.isNaN(a)) {
            Double corr = Math.max(STUB, Math.abs(a));
            series.addValue(corr, "PC" + (component + 1), "Date run");
        }
    }
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    JFreeChart chart = ChartFactory.createBarChart("", "Factors", "Component assoc.", series,
            PlotOrientation.VERTICAL, true, false, false);

    chart.getCategoryPlot().getRangeAxis().setRange(0, 1);
    BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer();
    renderer.setBasePaint(Color.white);
    renderer.setShadowVisible(false);
    chart.getCategoryPlot().setRangeGridlinesVisible(false);
    chart.getCategoryPlot().setDomainGridlinesVisible(false);
    ChartUtilities.applyCurrentTheme(chart);

    CategoryAxis domainAxis = chart.getCategoryPlot().getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    for (int i = 0; i < MAX_COMP; i++) {
        /*
         * Hue is straightforward; brightness is set medium to make it muted; saturation we vary from high to low.
         */
        float saturationDrop = (float) Math.min(1.0, i * 1.3f / MAX_COMP);
        renderer.setSeriesPaint(i, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f));

    }

    /*
     * Give figure more room .. up to a limit
     */
    int width = ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX;
    if (chart.getCategoryPlot().getCategories().size() > 3) {
        width = width + 40 * (chart.getCategoryPlot().getCategories().size() - 2);
    }
    int MAX_QC_IMAGE_SIZE_PX = 500;
    width = Math.min(width, MAX_QC_IMAGE_SIZE_PX);
    ChartUtilities.writeChartAsPNG(os, chart, width, ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX);
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

private boolean writePCAScree(OutputStream os, SVDValueObject svdo) throws Exception {
    /*/*from www  .  j  av a2 s .c  o m*/
     * Make a scree plot.
     */
    CategoryDataset series = this.getPCAScree(svdo);

    if (series.getColumnCount() == 0) {
        return false;
    }
    int MAX_COMPONENTS_FOR_SCREE = 10;
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    JFreeChart chart = ChartFactory.createBarChart("", "Component (up to" + MAX_COMPONENTS_FOR_SCREE + ")",
            "Fraction of var.", series, PlotOrientation.VERTICAL, false, false, false);

    BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer();
    renderer.setBasePaint(Color.white);
    renderer.setShadowVisible(false);
    chart.getCategoryPlot().setRangeGridlinesVisible(false);
    chart.getCategoryPlot().setDomainGridlinesVisible(false);
    ChartUtilities.writeChartAsPNG(os, chart, ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX,
            ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX);
    return true;
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

private boolean writeProbeCorrHistImage(OutputStream os, ExpressionExperiment ee) throws IOException {
    XYSeries series = this.getCorrelHist(ee);

    if (series == null || series.getItemCount() == 0) {
        return false;
    }/*ww  w.jav a 2  s . c om*/

    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
    xySeriesCollection.addSeries(series);
    JFreeChart chart = ChartFactory.createXYLineChart("", "Correlation", "Frequency", xySeriesCollection,
            PlotOrientation.VERTICAL, false, false, false);
    chart.getXYPlot().setRangeGridlinesVisible(false);
    chart.getXYPlot().setDomainGridlinesVisible(false);
    XYItemRenderer renderer = chart.getXYPlot().getRenderer();
    renderer.setBasePaint(Color.white);

    int size = (int) (ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX * 0.8);
    ChartUtilities.writeChartAsPNG(os, chart, size, size);

    return true;
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

/**
 * Has to handle the situation where there might be more than one ResultSet.
 *///from w  ww  .j av a  2 s . com
private boolean writePValueHistImage(OutputStream os, ExpressionExperiment ee, Long analysisId, Long rsId,
        String factorName) throws IOException {

    XYSeries series = this.getDiffExPvalueHistXYSeries(ee, analysisId, rsId, factorName);

    if (series == null) {
        return false;
    }

    XYSeriesCollection xySeriesCollection = new XYSeriesCollection(series);

    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    JFreeChart chart = ChartFactory.createXYLineChart("", "P-value", "Frequency", xySeriesCollection,
            PlotOrientation.VERTICAL, false, false, false);
    chart.getXYPlot().setRangeGridlinesVisible(false);
    chart.getXYPlot().setDomainGridlinesVisible(false);
    XYItemRenderer renderer = chart.getXYPlot().getRenderer();
    renderer.setBasePaint(Color.white);

    ChartUtilities.writeChartAsPNG(os, chart,
            (int) (ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX * 1.4),
            ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX);
    return true;
}