Example usage for org.jfree.chart.plot XYPlot setDomainGridlinePaint

List of usage examples for org.jfree.chart.plot XYPlot setDomainGridlinePaint

Introduction

In this page you can find the example usage for org.jfree.chart.plot XYPlot setDomainGridlinePaint.

Prototype

public void setDomainGridlinePaint(Paint paint) 

Source Link

Document

Sets the paint for the grid lines plotted against the domain axis, and sends a PlotChangeEvent to all registered listeners.

Usage

From source file:csds60analyzer.csds60analyzerGUI.java

public BufferedImage creaImagen() {
    BufferedImage imagen = null;/*  w  w  w  . j av  a 2s .c o  m*/
    try {
        SAXBuilder builder = new SAXBuilder(false);
        Document doc = null;
        TimeSeriesCollection datos = new TimeSeriesCollection();
        if (fichero != null) {
            doc = builder.build(fichero);
            Element raiz = doc.getRootElement();
            List<Element> dias = raiz.getChildren("dia");
            Iterator<Element> diasIT = dias.iterator();
            TimeSeries desayunoAntes = new TimeSeries("Desayuno antes");
            TimeSeries desayunoDespues = new TimeSeries("Desayuno despus");
            TimeSeries almuerzoAntes = new TimeSeries("Almuerzo antes");
            TimeSeries almuerzoDespues = new TimeSeries("Almuerzo despus");
            TimeSeries cenaAntes = new TimeSeries("Cena antes");
            TimeSeries cenaDespues = new TimeSeries("Cena despus");

            pdesayuno = 0;
            pdesant = 0;
            pdesdes = 0;
            palmuerzo = 0;
            palmant = 0;
            palmdes = 0;
            pcena = 0;
            pcenant = 0;
            pcendes = 0;

            contdesant = 0;
            contdesdes = 0;
            contalmant = 0;
            contalmdes = 0;
            contcenant = 0;
            contcendes = 0;

            while (diasIT.hasNext()) {
                Element diaActual = diasIT.next();
                Integer fechaActual = Integer.parseInt(diaActual.getChildText("fecha").substring(0, 10));

                Calendar fad = GregorianCalendar.getInstance();
                fad.setTimeInMillis(fechaActual.longValue() * 1000);

                int dia = fad.get(Calendar.DAY_OF_MONTH);
                int mes = fad.get(Calendar.MONTH) + 1;
                int ano = fad.get(Calendar.YEAR);

                if (diaActual.getChildren().toString().contains("desayunoantes")) {
                    int desayunoAntesActual = Integer.parseInt(diaActual.getChildText("desayunoantes"));
                    desayunoAntes.add(new Day(dia, mes, ano), desayunoAntesActual);
                    pdesant = pdesant + desayunoAntesActual;
                    contdesant++;
                }
                if (diaActual.getChildren().toString().contains("desayunodespues")) {
                    int desayunoDespuesActual = Integer.parseInt(diaActual.getChildText("desayunodespues"));
                    desayunoDespues.add(new Day(dia, mes, ano), desayunoDespuesActual);
                    pdesdes = pdesdes + desayunoDespuesActual;
                    contdesdes++;
                }
                if (diaActual.getChildren().toString().contains("almuerzoantes")) {
                    int almuerzoAntesActual = Integer.parseInt(diaActual.getChildText("almuerzoantes"));
                    almuerzoAntes.add(new Day(dia, mes, ano), almuerzoAntesActual);
                    palmant = palmant + almuerzoAntesActual;
                    contalmant++;
                }
                if (diaActual.getChildren().toString().contains("almuerzodespues")) {
                    int almuerzoDespuesActual = Integer.parseInt(diaActual.getChildText("almuerzodespues"));
                    almuerzoDespues.add(new Day(dia, mes, ano), almuerzoDespuesActual);
                    palmdes = palmdes + almuerzoDespuesActual;
                    contalmdes++;
                }
                if (diaActual.getChildren().toString().contains("cenaantes")) {
                    int cenaAntesActual = Integer.parseInt(diaActual.getChildText("cenaantes"));
                    cenaAntes.add(new Day(dia, mes, ano), cenaAntesActual);
                    pcenant = pcenant + cenaAntesActual;
                    contcenant++;
                }
                if (diaActual.getChildren().toString().contains("cenadespues")) {
                    int cenaDespuesActual = Integer.parseInt(diaActual.getChildText("cenadespues"));
                    cenaDespues.add(new Day(dia, mes, ano), cenaDespuesActual);
                    pcendes = pcendes + cenaDespuesActual;
                    contcendes++;
                }
            }
            //controlar la division por cero
            if ((contdesant + contdesdes) > 0)
                pdesayuno = (pdesant + pdesdes) / (contdesant + contdesdes);
            if (contdesant > 0)
                pdesant = pdesant / contdesant;
            if (contdesdes > 0)
                pdesdes = pdesdes / contdesdes;
            if ((contalmant + contalmdes) > 0)
                palmuerzo = (palmant + palmdes) / (contalmant + contalmdes);
            if (contalmant > 0)
                palmant = palmant / contalmant;
            if (contalmdes > 0)
                palmdes = palmdes / contalmdes;
            if ((contcenant + contcendes) > 0)
                pcena = (pcenant + pcendes) / (contcenant + contcendes);
            if (contcenant > 0)
                pcenant = pcenant / contcenant;
            if (contcendes > 0)
                pcendes = pcendes / contcendes;
            datos.addSeries(desayunoAntes);
            datos.addSeries(desayunoDespues);
            datos.addSeries(almuerzoAntes);
            datos.addSeries(almuerzoDespues);
            datos.addSeries(cenaAntes);
            datos.addSeries(cenaDespues);
        }
        JFreeChart graficaJfree = ChartFactory.createTimeSeriesChart("Anlisis", " ", "Glucosa (mg)", datos,
                true, true, false);
        XYPlot plot = (XYPlot) graficaJfree.getPlot();
        plot.setBackgroundPaint(Color.getHSBColor(0f, 0f, .88f));
        plot.setDomainGridlinePaint(Color.getHSBColor(0f, 0f, .35f));
        plot.setDomainTickBandPaint(Color.getHSBColor(0f, 0f, .93f));
        plot.setOutlinePaint(Color.getHSBColor(0f, 0f, 0.35f));
        plot.setRangeGridlinePaint(Color.getHSBColor(0f, 0f, 0.35f));
        XYLineAndShapeRenderer plot2 = (XYLineAndShapeRenderer) plot.getRenderer();
        if (!CBdesayunoantes.getState())
            plot2.setSeriesLinesVisible(0, false);
        plot2.setSeriesPaint(0, Color.getHSBColor(.3f, 1f, .5f));
        //plot2.setSeriesStroke(0,new BasicStroke(2.0f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,1.0f));
        if (!CBdesayunodespues.getState())
            plot2.setSeriesLinesVisible(1, false);
        plot2.setSeriesPaint(1, Color.getHSBColor(.2f, 1f, .9f));
        if (!CBalmuerzoantes.getState())
            plot2.setSeriesLinesVisible(2, false);
        plot2.setSeriesPaint(2, Color.getHSBColor(.0f, 1f, .6f));
        if (!CBalmuerzodespues.getState())
            plot2.setSeriesLinesVisible(3, false);
        plot2.setSeriesPaint(3, Color.getHSBColor(.0f, 1f, .9f));
        if (!CBcenaantes.getState())
            plot2.setSeriesLinesVisible(4, false);
        plot2.setSeriesPaint(4, Color.getHSBColor(.6f, 1f, .4f));
        if (!CBcenadespues.getState())
            plot2.setSeriesLinesVisible(5, false);
        plot2.setSeriesPaint(5, Color.getHSBColor(.6f, 1f, 1f));
        imagen = graficaJfree.createBufferedImage(800, 600);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return imagen;
}

From source file:dk.netarkivet.harvester.harvesting.monitor.StartedJobHistoryChartGen.java

/**
 * Generates a chart in PNG format.//from  w  w  w . j av a2s .c  om
 * @param outputFile the output file, it should exist.
 * @param pxWidth the image width in pixels.
 * @param pxHeight the image height in pixels.
 * @param chartTitle the chart title, may be null.
 * @param xAxisTitle the x axis title
 * @param yDataSeriesRange the axis range (null for auto)
 * @param yDataSeriesTitles the Y axis titles.
 * @param timeValuesInSeconds the time values in seconds
 * @param yDataSeries the Y axis value series.
 * @param yDataSeriesColors the Y axis value series drawing colors.
 * @param yDataSeriesTickSuffix TODO explain argument yDataSeriesTickSuffix
 * @param drawBorder draw, or not, the border.
 * @param backgroundColor the chart background color.
 */
final void generatePngChart(File outputFile, int pxWidth, int pxHeight, String chartTitle, String xAxisTitle,
        String[] yDataSeriesTitles, double[] timeValuesInSeconds, double[][] yDataSeriesRange,
        double[][] yDataSeries, Color[] yDataSeriesColors, String[] yDataSeriesTickSuffix, boolean drawBorder,
        Color backgroundColor) {

    // Domain axis
    NumberAxis xAxis = new NumberAxis(xAxisTitle);
    xAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    xAxis.setLabelPaint(Color.black);
    xAxis.setTickLabelPaint(Color.black);

    double maxSeconds = getMaxValue(timeValuesInSeconds);
    TimeAxisResolution xAxisRes = TimeAxisResolution.findTimeUnit(maxSeconds);
    xAxis.setTickUnit(new NumberTickUnit(xAxisRes.tickStep));
    double[] scaledTimeValues = xAxisRes.scale(timeValuesInSeconds);

    String tickSymbol = I18N.getString(locale, "running.job.details.chart.timeunit.symbol." + xAxisRes.name());
    xAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + tickSymbol + "'"));

    // First dataset
    String firstDataSetTitle = yDataSeriesTitles[0];
    XYDataset firstDataSet = createXYDataSet(firstDataSetTitle, scaledTimeValues, yDataSeries[0]);
    Color firstDataSetColor = yDataSeriesColors[0];

    // First range axis
    NumberAxis firstYAxis = new NumberAxis(firstDataSetTitle);

    firstYAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    setAxisRange(firstYAxis, yDataSeriesRange[0]);
    firstYAxis.setLabelPaint(firstDataSetColor);
    firstYAxis.setTickLabelPaint(firstDataSetColor);
    String firstAxisTickSuffix = yDataSeriesTickSuffix[0];
    if (firstAxisTickSuffix != null && !firstAxisTickSuffix.isEmpty()) {
        firstYAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + firstAxisTickSuffix + "'"));
    }

    // Create the plot with domain axis and first range axis
    XYPlot plot = new XYPlot(firstDataSet, xAxis, firstYAxis, null);

    XYLineAndShapeRenderer firstRenderer = new XYLineAndShapeRenderer(true, false);
    plot.setRenderer(firstRenderer);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    firstRenderer.setSeriesPaint(0, firstDataSetColor);

    // Now iterate on next axes
    for (int i = 1; i < yDataSeries.length; i++) {
        // Create axis
        String seriesTitle = yDataSeriesTitles[i];
        Color seriesColor = yDataSeriesColors[i];
        NumberAxis yAxis = new NumberAxis(seriesTitle);

        yAxis.setFixedDimension(CHART_AXIS_DIMENSION);
        setAxisRange(yAxis, yDataSeriesRange[i]);

        yAxis.setLabelPaint(seriesColor);
        yAxis.setTickLabelPaint(seriesColor);

        String yAxisTickSuffix = yDataSeriesTickSuffix[i];
        if (yAxisTickSuffix != null && !yAxisTickSuffix.isEmpty()) {
            yAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + yAxisTickSuffix + "'"));
        }

        // Create dataset and add axis to plot
        plot.setRangeAxis(i, yAxis);
        plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_LEFT);
        plot.setDataset(i, createXYDataSet(seriesTitle, scaledTimeValues, yDataSeries[i]));
        plot.mapDatasetToRangeAxis(i, i);
        XYItemRenderer renderer = new StandardXYItemRenderer();
        renderer.setSeriesPaint(0, seriesColor);
        plot.setRenderer(i, renderer);
    }

    // Create the chart
    JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, false);

    // Customize rendering
    chart.setBackgroundPaint(Color.white);
    chart.setBorderVisible(true);
    chart.setBorderPaint(Color.BLACK);

    // Render image
    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, pxWidth, pxHeight);
    } catch (IOException e) {
        LOG.error("Chart export failed", e);
    }
}

From source file:com.vgi.mafscaling.VECalc.java

protected void createChart(JPanel plotPanel, String xAxisName, String yAxisName) {
    JFreeChart chart = ChartFactory.createScatterPlot(null, null, null, null, PlotOrientation.VERTICAL, false,
            true, false);/*  ww w . j a  v  a 2  s. c  o  m*/
    chart.setBorderVisible(true);

    chartPanel = new ChartPanel(chart, true, true, true, true, true);
    chartPanel.setAutoscrolls(true);
    chartPanel.setMouseZoomable(false);

    GridBagConstraints gbl_chartPanel = new GridBagConstraints();
    gbl_chartPanel.anchor = GridBagConstraints.CENTER;
    gbl_chartPanel.insets = new Insets(3, 3, 3, 3);
    gbl_chartPanel.weightx = 1.0;
    gbl_chartPanel.weighty = 1.0;
    gbl_chartPanel.fill = GridBagConstraints.BOTH;
    gbl_chartPanel.gridx = 0;
    gbl_chartPanel.gridy = 1;
    plotPanel.add(chartPanel, gbl_chartPanel);

    XYLineAndShapeRenderer lineRenderer = new XYLineAndShapeRenderer();
    lineRenderer.setUseFillPaint(true);
    lineRenderer.setBaseToolTipGenerator(
            new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new DecimalFormat("0.00"), new DecimalFormat("0.00")));

    Stroke stroke = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, null, 0.0f);
    lineRenderer.setSeriesStroke(0, stroke);
    lineRenderer.setSeriesPaint(0, Color.RED);
    lineRenderer.setSeriesShape(0, ShapeUtilities.createDiamond((float) 2.5));

    lineRenderer.setLegendItemLabelGenerator(new StandardXYSeriesLabelGenerator() {
        private static final long serialVersionUID = 7593430826693873496L;

        public String generateLabel(XYDataset dataset, int series) {
            XYSeries xys = ((XYSeriesCollection) dataset).getSeries(series);
            return xys.getDescription();
        }
    });

    NumberAxis xAxis = new NumberAxis(xAxisName);
    xAxis.setAutoRangeIncludesZero(false);
    NumberAxis yAxis = new NumberAxis(yAxisName);
    yAxis.setAutoRangeIncludesZero(false);

    XYSeriesCollection lineDataset = new XYSeriesCollection();

    XYPlot plot = chart.getXYPlot();
    plot.setRangePannable(true);
    plot.setDomainPannable(true);
    plot.setDomainGridlinePaint(Color.DARK_GRAY);
    plot.setRangeGridlinePaint(Color.DARK_GRAY);
    plot.setBackgroundPaint(new Color(224, 224, 224));

    plot.setDataset(0, lineDataset);
    plot.setRenderer(0, lineRenderer);
    plot.setDomainAxis(0, xAxis);
    plot.setRangeAxis(0, yAxis);
    plot.mapDatasetToDomainAxis(0, 0);
    plot.mapDatasetToRangeAxis(0, 0);

    LegendTitle legend = new LegendTitle(plot.getRenderer());
    legend.setItemFont(new Font("Arial", 0, 10));
    legend.setPosition(RectangleEdge.TOP);
    chart.addLegend(legend);
}

From source file:org.n52.server.sos.render.DiagramRenderer.java

/**
 * <pre>/*from  w  w w  .j a  va2s .  c  o m*/
 * dataset :=  associated to one range-axis;
 * corresponds to one observedProperty;
 * may contain multiple series;
 * series :=   corresponds to a time series for one foi
 * </pre>
 * 
 * .
 * 
 * @param entireCollMap
 *            the entire coll map
 * @param options
 *            the options
 * @param begin
 *            the begin
 * @param end
 *            the end
 * @param compress
 * @return the j free chart
 */
public JFreeChart renderChart(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        Calendar begin, Calendar end, boolean compress) {

    DesignDescriptionList designDescriptions = buildUpDesignDescriptionList(options);

    /*** FIRST RUN ***/
    JFreeChart chart = initializeTimeSeriesChart();
    chart.setBackgroundPaint(Color.white);

    if (!this.isOverview) {
        chart.addSubtitle(new TextTitle(ConfigurationContext.COPYRIGHT, new Font(LABEL_FONT, Font.PLAIN, 9),
                Color.black, RectangleEdge.BOTTOM, HorizontalAlignment.RIGHT, VerticalAlignment.BOTTOM,
                new RectangleInsets(0, 0, 20, 20)));
    }
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.setDomainGridlinesVisible(options.getGrid());
    plot.setRangeGridlinesVisible(options.getGrid());

    // add additional datasets:
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setRange(begin.getTime(), end.getTime());
    dateAxis.setDateFormatOverride(new SimpleDateFormat());

    // add all axes
    String[] phenomenaIds = options.getAllPhenomenIds();
    // all the axis indices to map them later
    HashMap<String, Integer> axes = new HashMap<String, Integer>();
    for (int i = 0; i < phenomenaIds.length; i++) {
        axes.put(phenomenaIds[i], i);
        plot.setRangeAxis(i, new NumberAxis(phenomenaIds[i]));
    }

    // list range markers
    ArrayList<ValueMarker> referenceMarkers = new ArrayList<ValueMarker>();
    HashMap<String, double[]> referenceBounds = new HashMap<String, double[]>();

    // create all TS collections
    for (int i = 0; i < options.getProperties().size(); i++) {

        TimeseriesProperties prop = options.getProperties().get(i);

        String phenomenonId = prop.getPhenomenon();

        TimeSeriesCollection dataset = createDataset(entireCollMap, prop, phenomenonId, compress);
        dataset.setGroup(new DatasetGroup(prop.getTimeseriesId()));
        XYDataset additionalDataset = dataset;

        NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenomenonId));

        if (this.isOverview) {
            axe.setAutoRange(true);
            axe.setAutoRangeIncludesZero(false);
        } else if (prop.getAxisUpperBound() == prop.getAxisLowerBound() || prop.isAutoScale()) {
            if (prop.isZeroScaled()) {
                axe.setAutoRangeIncludesZero(true);
            } else {
                axe.setAutoRangeIncludesZero(false);
            }
        } else {
            if (prop.isZeroScaled()) {
                if (axe.getUpperBound() < prop.getAxisUpperBound()) {
                    axe.setUpperBound(prop.getAxisUpperBound());
                }
                if (axe.getLowerBound() > prop.getAxisLowerBound()) {
                    axe.setLowerBound(prop.getAxisLowerBound());
                }
            } else {
                axe.setRange(prop.getAxisLowerBound(), prop.getAxisUpperBound());
                axe.setAutoRangeIncludesZero(false);
            }
        }

        plot.setDataset(i, additionalDataset);
        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));

        // set bounds new for reference values
        if (!referenceBounds.containsKey(phenomenonId)) {
            double[] bounds = new double[] { axe.getLowerBound(), axe.getUpperBound() };
            referenceBounds.put(phenomenonId, bounds);
        } else {
            double[] bounds = referenceBounds.get(phenomenonId);
            if (bounds[0] >= axe.getLowerBound()) {
                bounds[0] = axe.getLowerBound();
            }
            if (bounds[1] <= axe.getUpperBound()) {
                bounds[1] = axe.getUpperBound();
            }
        }

        double[] bounds = referenceBounds.get(phenomenonId);
        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                Double value = prop.getRefValue(string).getValue();
                if (value <= bounds[0]) {
                    bounds[0] = value;
                } else if (value >= bounds[1]) {
                    bounds[1] = value;
                }
            }
        }

        Axis axis = prop.getAxis();
        if (axis == null) {
            axis = new Axis(axe.getUpperBound(), axe.getLowerBound());
        } else if (prop.isAutoScale()) {
            axis.setLowerBound(axe.getLowerBound());
            axis.setUpperBound(axe.getUpperBound());
            axis.setMaxY(axis.getMaxY());
            axis.setMinY(axis.getMinY());
        }
        prop.setAxisData(axis);
        this.axisMapping.put(prop.getTimeseriesId(), axis);

        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                referenceMarkers.add(new ValueMarker(prop.getRefValue(string).getValue(),
                        Color.decode(prop.getRefValue(string).getColor()),
                        new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f)));
            }
        }

        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));
    }

    for (ValueMarker valueMarker : referenceMarkers) {
        plot.addRangeMarker(valueMarker);
    }

    // show actual time
    ValueMarker nowMarker = new ValueMarker(System.currentTimeMillis(), Color.orange,
            new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f));
    plot.addDomainMarker(nowMarker);

    if (!this.isOverview) {
        Iterator<Entry<String, double[]>> iterator = referenceBounds.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, double[]> boundsEntry = iterator.next();
            String phenId = boundsEntry.getKey();
            NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenId));
            axe.setAutoRange(true);
            // add a margin 
            double marginOffset = (boundsEntry.getValue()[1] - boundsEntry.getValue()[0]) / 25;
            boundsEntry.getValue()[0] -= marginOffset;
            boundsEntry.getValue()[1] += marginOffset;
            axe.setRange(boundsEntry.getValue()[0], boundsEntry.getValue()[1]);
        }
    }

    /**** SECOND RUN ***/

    // set domain axis labels:
    plot.getDomainAxis().setLabelFont(label);
    plot.getDomainAxis().setLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setTickLabelFont(tickLabelDomain);
    plot.getDomainAxis().setTickLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setLabel(designDescriptions.getDomainAxisLabel());

    // define the design for each series:
    for (int datasetIndex = 0; datasetIndex < plot.getDatasetCount(); datasetIndex++) {
        TimeSeriesCollection dataset = (TimeSeriesCollection) plot.getDataset(datasetIndex);

        for (int seriesIndex = 0; seriesIndex < dataset.getSeriesCount(); seriesIndex++) {

            String timeseriesId = (String) dataset.getSeries(seriesIndex).getKey();
            RenderingDesign dd = designDescriptions.get(timeseriesId);

            if (dd != null) {

                // LINESTYLE:
                String lineStyle = dd.getLineStyle();
                int width = dd.getLineWidth();
                if (this.isOverview) {
                    width = width / 2;
                    width = (width == 0) ? 1 : width;
                }
                // "1" is lineStyle "line"
                if (lineStyle.equalsIgnoreCase(LINE)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, false);
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                }
                // "2" is lineStyle "area"
                else if (lineStyle.equalsIgnoreCase(AREA)) {
                    plot.setRenderer(datasetIndex, new XYAreaRenderer());
                }
                // "3" is lineStyle "dotted"
                else if (lineStyle.equalsIgnoreCase(DOTTED)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(false, true);
                    ren.setShape(new Ellipse2D.Double(-width, -width, 2 * width, 2 * width));
                    plot.setRenderer(datasetIndex, ren);

                }
                // "4" is dashed
                else if (lineStyle.equalsIgnoreCase("4")) {
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    renderer.setSeriesStroke(0, new BasicStroke(width, BasicStroke.CAP_ROUND,
                            BasicStroke.JOIN_ROUND, 1.0f, new float[] { 4.0f * width, 4.0f * width }, 0.0f));
                    plot.setRenderer(datasetIndex, renderer);
                } else if (lineStyle.equalsIgnoreCase("5")) {
                    // lines and dots
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, true);
                    int thickness = 2 * width;
                    ren.setShape(new Ellipse2D.Double(-width, -width, thickness, thickness));
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                } else {
                    // default is lineStyle "line"
                    plot.setRenderer(datasetIndex, new XYLineAndShapeRenderer(true, false));
                }

                plot.getRenderer(datasetIndex).setSeriesPaint(seriesIndex, dd.getColor());

                // plot.getRenderer(datasetIndex).setShapesVisible(true);

                XYToolTipGenerator toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();
                XYURLGenerator urlGenerator = new MetadataInURLGenerator(designDescriptions);

                plot.getRenderer(datasetIndex).setBaseToolTipGenerator(toolTipGenerator);
                plot.getRenderer(datasetIndex).setURLGenerator(urlGenerator);

                // GRID:
                // PROBLEM: JFreeChart only allows to switch the grid on/off
                // for the whole XYPlot. And the
                // grid will always be displayed for the first series in the
                // plot. I'll always show the
                // grid.
                // --> plot.setDomainGridlinesVisible(visible)

                // RANGE AXIS LABELS:
                if (isOverview) {
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelsVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setTickMarksVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setVisible(false);
                } else {
                    plot.getRangeAxisForDataset(datasetIndex).setLabelFont(label);
                    plot.getRangeAxisForDataset(datasetIndex).setLabelPaint(LABEL_COLOR);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelFont(tickLabelDomain);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelPaint(LABEL_COLOR);
                    StringBuilder unitOfMeasure = new StringBuilder();
                    unitOfMeasure.append(dd.getPhenomenon().getLabel());
                    String uomLabel = dd.getUomLabel();
                    if (uomLabel != null && !uomLabel.isEmpty()) {
                        unitOfMeasure.append(" (").append(uomLabel).append(")");
                    }
                    plot.getRangeAxisForDataset(datasetIndex).setLabel(unitOfMeasure.toString());
                }
            }
        }
    }
    return chart;
}

From source file:edu.ucla.stat.SOCR.analyses.gui.Chart.java

private JFreeChart createLineChart(String title, String xLabel, String yLabel, XYDataset dataset,
        String other) {//from  ww  w.j av a 2s . com

    // create the chart...
    JFreeChart chart = ChartFactory.createXYLineChart(title, // chart title
            xLabel, // domain axis label
            yLabel, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    XYPlot plot = chart.getXYPlot();
    chart.setBackgroundPaint(Color.white);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.lightGray);
    //plot.setNoDataMessage("No data available");

    // customise the range axis...

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
    domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setUpperMargin(0.02);
    rangeAxis.setLowerMargin(0.02);
    domainAxis.setUpperMargin(0.02);
    domainAxis.setLowerMargin(0.02);

    // customise the renderer...
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseShapesVisible(true);
    renderer.setBaseLinesVisible(true);
    renderer.setDrawOutlines(true);
    renderer.setBaseShapesFilled(true);
    renderer.setUseFillPaint(true);
    renderer.setBaseFillPaint(Color.white);

    if (other.toLowerCase().indexOf("noline") != -1) {
        renderer.setBaseShapesVisible(true);
        renderer.setBaseLinesVisible(false);
    }

    if (other.toLowerCase().indexOf("noshape") != -1) {
        renderer.setBaseShapesVisible(false);
        renderer.setBaseLinesVisible(true);
    }

    if (other.toLowerCase().indexOf("excludeszero") != -1) {
        rangeAxis.setAutoRangeIncludesZero(false);
        domainAxis.setAutoRangeIncludesZero(false);
    }

    return chart;
}

From source file:course_generator.param.frmEditCurve.java

/**
 * Create the chart//  w  w w  .java  2s .co  m
 * @param dataset Dataset to display
 * @return Return a JFreeChart object
 */
private JFreeChart CreateChartProfil(XYDataset dataset) {
    JFreeChart chart = ChartFactory.createXYAreaChart("", bundle.getString("frmEditCurve.chart.slope"), //"Slope"  x axis label
            bundle.getString("frmEditCurve.chart.speed"), //"speed"  y axis label
            dataset, // data
            PlotOrientation.VERTICAL, false, // include legend
            true, // tooltips
            false // urls
    );

    chart.setBackgroundPaint(Color.white); // Panel background color
    XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.gray);
    plot.setRangeGridlinePaint(Color.gray);

    // XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    XYAreaRenderer renderer = new XYAreaRenderer();
    // Green (safe color)
    renderer.setSeriesPaint(0, new Color(0x99, 0xff, 0x00));
    renderer.setOutline(true);
    // Width of the outline
    renderer.setSeriesOutlineStroke(0, new BasicStroke(2.0f));
    plot.setRenderer(renderer);

    // NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    // rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    return chart;
}

From source file:com.igalia.java.zk.components.JFreeChartEngine.java

public byte[] drawChart(Object data) {
    Chart chart = (Chart) data;//  w ww. j a v a  2s.  c  o m
    ChartImpl impl = getChartImpl(chart);
    JFreeChart jfchart = impl.createChart(chart);

    Plot plot = (Plot) jfchart.getPlot();
    float alpha = (float) (((float) chart.getFgAlpha()) / 255);
    plot.setForegroundAlpha(alpha);

    alpha = (float) (((float) chart.getBgAlpha()) / 255);
    plot.setBackgroundAlpha(alpha);

    int[] bgRGB = chart.getBgRGB();
    if (bgRGB != null) {
        plot.setBackgroundPaint(new Color(bgRGB[0], bgRGB[1], bgRGB[2], chart.getBgAlpha()));
    }

    int[] paneRGB = chart.getPaneRGB();
    if (paneRGB != null) {
        jfchart.setBackgroundPaint(new Color(paneRGB[0], paneRGB[1], paneRGB[2], chart.getPaneAlpha()));
    }

    //since 3.6.3, JFreeChart 1.0.13 change default fonts which does not support Chinese, allow
    //developer to set font.

    //title font
    final Font tfont = chart.getTitleFont();
    if (tfont != null) {
        jfchart.getTitle().setFont(tfont);
    }

    //legend font
    final Font lfont = chart.getLegendFont();
    if (lfont != null) {
        jfchart.getLegend().setItemFont(lfont);
    }

    if (plot instanceof CategoryPlot) {
        final CategoryPlot cplot = (CategoryPlot) plot;
        cplot.setRangeGridlinePaint(new Color(0xc0, 0xc0, 0xc0));

        //Domain axis(x axis)
        final Font xlbfont = chart.getXAxisFont();
        final Font xtkfont = chart.getXAxisTickFont();
        if (xlbfont != null) {
            cplot.getDomainAxis().setLabelFont(xlbfont);
        }
        if (xtkfont != null) {
            cplot.getDomainAxis().setTickLabelFont(xtkfont);
        }

        Color[] colorMappings = (Color[]) chart.getAttribute("series-color-mappings");
        if (colorMappings != null) {
            for (int ii = 0; ii < colorMappings.length; ii++) {
                cplot.getRenderer().setSeriesPaint(ii, colorMappings[ii]);
            }
        }

        Double lowerBound = (Double) chart.getAttribute("range-axis-lower-bound");
        if (lowerBound != null) {
            cplot.getRangeAxis().setAutoRange(false);
            cplot.getRangeAxis().setLowerBound(lowerBound);
        }

        Double upperBound = (Double) chart.getAttribute("range-axis-upper-bound");
        if (upperBound != null) {
            cplot.getRangeAxis().setAutoRange(false);
            cplot.getRangeAxis().setUpperBound(upperBound);
        }

        //Range axis(y axis)
        final Font ylbfont = chart.getYAxisFont();
        final Font ytkfont = chart.getYAxisTickFont();
        if (ylbfont != null) {
            cplot.getRangeAxis().setLabelFont(ylbfont);
        }
        if (ytkfont != null) {
            cplot.getRangeAxis().setTickLabelFont(ytkfont);
        }
    } else if (plot instanceof XYPlot) {
        final XYPlot xyplot = (XYPlot) plot;
        xyplot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        xyplot.setDomainGridlinePaint(Color.LIGHT_GRAY);

        //Domain axis(x axis)
        final Font xlbfont = chart.getXAxisFont();
        final Font xtkfont = chart.getXAxisTickFont();
        if (xlbfont != null) {
            xyplot.getDomainAxis().setLabelFont(xlbfont);
        }
        if (xtkfont != null) {
            xyplot.getDomainAxis().setTickLabelFont(xtkfont);
        }

        //Range axis(y axis)
        final Font ylbfont = chart.getYAxisFont();
        final Font ytkfont = chart.getYAxisTickFont();
        if (ylbfont != null) {
            xyplot.getRangeAxis().setLabelFont(ylbfont);
        }
        if (ytkfont != null) {
            xyplot.getRangeAxis().setTickLabelFont(ytkfont);
        }
    } else if (plot instanceof PiePlot) {
        plot.setOutlineStroke(null);
    }

    //callbacks for each area
    ChartRenderingInfo jfinfo = new ChartRenderingInfo();
    BufferedImage bi = jfchart.createBufferedImage(chart.getIntWidth(), chart.getIntHeight(),
            Transparency.TRANSLUCENT, jfinfo);

    //remove old areas
    if (chart.getChildren().size() > 20)
        chart.invalidate(); //improve performance if too many chart
    chart.getChildren().clear();

    if (Events.isListened(chart, Events.ON_CLICK, false) || chart.isShowTooltiptext()) {
        int j = 0;
        String preUrl = null;
        for (Iterator it = jfinfo.getEntityCollection().iterator(); it.hasNext();) {
            ChartEntity ce = (ChartEntity) it.next();
            final String url = ce.getURLText();

            //workaround JFreeChart's bug (skip replicate areas)
            if (url != null) {
                if (preUrl == null) {
                    preUrl = url;
                } else if (url.equals(preUrl)) { //start replicate, skip
                    break;
                }
            }

            //1. JFreeChartEntity area cover the whole chart, will "mask" other areas
            //2. LegendTitle area cover the whole legend, will "mask" each legend
            //3. PlotEntity cover the whole chart plotting araa, will "mask" each bar/line/area
            if (!(ce instanceof JFreeChartEntity)
                    && !(ce instanceof TitleEntity && ((TitleEntity) ce).getTitle() instanceof LegendTitle)
                    && !(ce instanceof PlotEntity)) {
                Area area = new Area();
                area.setParent(chart);
                area.setCoords(ce.getShapeCoords());
                area.setShape(ce.getShapeType());
                area.setId("area_" + chart.getId() + '_' + (j++));
                if (chart.isShowTooltiptext() && ce.getToolTipText() != null) {
                    area.setTooltiptext(ce.getToolTipText());
                }
                area.setAttribute("url", ce.getURLText());
                impl.render(chart, area, ce);
                if (chart.getAreaListener() != null) {
                    try {
                        chart.getAreaListener().onRender(area, ce);
                    } catch (Exception ex) {
                        throw UiException.Aide.wrap(ex);
                    }
                }
            }
        }
    }
    //clean up the "LEGEND_SEQ"
    //used for workaround LegendItemEntity.getSeries() always return 0
    //used for workaround TickLabelEntity no information
    chart.removeAttribute("LEGEND_SEQ");
    chart.removeAttribute("TICK_SEQ");

    try {
        //encode into png image format byte array
        return EncoderUtil.encode(bi, ImageFormat.PNG, true);
    } catch (java.io.IOException ex) {
        throw UiException.Aide.wrap(ex);
    }
}

From source file:edu.ucla.stat.SOCR.analyses.gui.Chart.java

private JFreeChart createLineChart(String title, String xLabel, String yLabel, XYDataset dataset,
        Color[] colors, String other) {

    // create the chart...
    JFreeChart chart = ChartFactory.createXYLineChart(title, // chart title
            xLabel, // domain axis label
            yLabel, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );//from w  w w . j  av a 2 s.c  om

    XYPlot plot = chart.getXYPlot();
    chart.setBackgroundPaint(Color.white);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.lightGray);
    //plot.setNoDataMessage("No data available");

    // customise the range axis...

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
    domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setUpperMargin(0.02);
    rangeAxis.setLowerMargin(0.02);
    domainAxis.setUpperMargin(0.02);
    domainAxis.setLowerMargin(0.02);

    // customise the renderer...
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseShapesVisible(true);
    renderer.setBaseLinesVisible(true);
    renderer.setDrawOutlines(true);
    renderer.setBaseShapesFilled(true);
    renderer.setUseFillPaint(true);
    renderer.setBaseFillPaint(Color.white);

    for (int i = 0; i < colors.length; i++) {
        renderer.setSeriesPaint(i, colors[i]);
    }

    if (other.toLowerCase().indexOf("noline") != -1) {
        renderer.setBaseShapesVisible(true);
        renderer.setBaseLinesVisible(false);
    }

    if (other.toLowerCase().indexOf("noshape") != -1) {
        renderer.setBaseShapesVisible(false);
        renderer.setBaseLinesVisible(true);
    }

    if (other.toLowerCase().indexOf("excludeszero") != -1) {
        rangeAxis.setAutoRangeIncludesZero(false);
        domainAxis.setAutoRangeIncludesZero(false);
    }

    if (other.toLowerCase().indexOf("color") != -1) {
        renderer.setBaseShapesVisible(false);
        renderer.setBaseLinesVisible(true);
    }

    return chart;
}

From source file:edu.ucla.stat.SOCR.analyses.gui.Chart.java

private JFreeChart createLineAndDotChart(String title, String xLabel, String yLabel, XYDataset dataset,
        int numberOfLines, Color[] lineColors, int numberOfDotsGroups, Color[] dotColors, String other) {

    boolean legend = true;
    if (other.toLowerCase().indexOf("noledend") != -1) {
        legend = false;//w ww  .  j a v a 2s .  c om
    }

    // create the chart...
    JFreeChart chart = ChartFactory.createXYLineChart(title, // chart title
            xLabel, // domain axis label
            yLabel, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            legend, // include legend
            true, // tooltips
            false // urls
    );

    XYPlot plot = chart.getXYPlot();
    chart.setBackgroundPaint(Color.white);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.lightGray);
    //plot.setNoDataMessage("No data available");

    // customise the range axis...

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
    domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    rangeAxis.setUpperMargin(0.02);
    rangeAxis.setLowerMargin(0.02);
    domainAxis.setUpperMargin(0.02);
    domainAxis.setLowerMargin(0.02);

    // customise the renderer...
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    for (int i = 0; i < numberOfLines; i++) {
        renderer.setSeriesShapesVisible(i, false);
        renderer.setSeriesLinesVisible(i, true);
    }
    for (int i = numberOfLines; i < numberOfLines + numberOfDotsGroups; i++) {
        renderer.setSeriesShapesVisible(i, true);
        renderer.setSeriesLinesVisible(i, false);
    }
    // renderer.setDrawOutlines(true);
    // renderer.setBaseShapesFilled(true);
    //   renderer.setUseFillPaint(true);
    //  renderer.setFillPaint(Color.white);

    //set line color
    for (int i = 0; i < lineColors.length; i++) {
        renderer.setSeriesPaint(i, lineColors[i]);
    }

    //    set dot color
    for (int i = 0; i < dotColors.length; i++) {
        renderer.setSeriesPaint(numberOfLines + i, dotColors[i]);
    }

    if (other.toLowerCase().indexOf("excludeszero") != -1) {
        rangeAxis.setAutoRangeIncludesZero(false);
        domainAxis.setAutoRangeIncludesZero(false);
    }

    return chart;
}

From source file:code.google.gclogviewer.GCLogViewer.java

private JFreeChart createGCTrendChart(GCLogData data) {
    XYDataset gcTrendDataset = createGCTrendDataset(data, null);
    JFreeChart chart = ChartFactory.createXYLineChart("GC Trend", "Time(S)", "Pause Time(ms)", gcTrendDataset,
            PlotOrientation.VERTICAL, true, true, false);
    chart.setBackgroundPaint(java.awt.Color.white);
    chart.setBorderVisible(true);//  w  w  w.ja  v  a2s  .  co m
    chart.setBorderPaint(java.awt.Color.BLACK);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(java.awt.Color.lightGray);
    plot.setDomainGridlinePaint(java.awt.Color.white);
    plot.setRangeGridlinePaint(java.awt.Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.getRangeAxis().setFixedDimension(15.0);
    return chart;
}