Example usage for org.jfree.chart.title LegendTitle setPosition

List of usage examples for org.jfree.chart.title LegendTitle setPosition

Introduction

In this page you can find the example usage for org.jfree.chart.title LegendTitle setPosition.

Prototype

public void setPosition(RectangleEdge position) 

Source Link

Document

Sets the position for the title and sends a TitleChangeEvent to all registered listeners.

Usage

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

@Override
public void updatePlotter() {
    prepareData();// ww  w . j  av  a2s .  c  om
    JFreeChart chart;
    if (axis[X_AXIS] >= 0 && axis[Y_AXIS] >= 0) {
        if (nominal) {
            int size = dataSet.getSeriesCount();
            chart = ChartFactory.createScatterPlot(null, // chart title
                    null, // domain axis label
                    null, // range axis label
                    dataSet, // data
                    PlotOrientation.VERTICAL, // orientation
                    colorColumn >= 0 && size < 100 ? true : false, // include legend
                    true, // tooltips
                    false // URLs
            );

            // renderer settings
            try {
                chart.getXYPlot().setRenderer(getItemRenderer(nominal, size, this.minColor, this.maxColor));
            } catch (Exception e) {
                // do nothing
            }

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

                BlockContainer wrapper = new BlockContainer(new BorderArrangement());

                LabelBlock title = new LabelBlock(getDataTable().getColumnName(colorColumn),
                        new Font("SansSerif", Font.BOLD, 12));
                title.setPadding(0, 5, 5, 5);
                wrapper.add(title, RectangleEdge.LEFT);

                BlockContainer items = legend.getItemContainer();
                wrapper.add(items, RectangleEdge.RIGHT);

                legend.setWrapper(wrapper);
            }
        } else {

            chart = ChartFactory.createScatterPlot(null, // chart title
                    null, // domain axis label
                    null, // range axis label
                    dataSet, // data
                    PlotOrientation.VERTICAL, // orientation
                    false, // include legend
                    true, // tooltips
                    false // URLs
            );

            // renderer settings
            try {
                chart.getXYPlot().setRenderer(getItemRenderer(nominal, -1, minColor, maxColor));
            } catch (Exception e) {
                // do nothing
            }

            LegendTitle legendTitle = new LegendTitle(chart.getXYPlot().getRenderer()) {

                private static final long serialVersionUID = 1288380309936848376L;

                @Override
                public Object draw(java.awt.Graphics2D g2, java.awt.geom.Rectangle2D area,
                        java.lang.Object params) {
                    if (dataTable.isDate(colorColumn) || dataTable.isTime(colorColumn)
                            || dataTable.isDateTime(colorColumn)) {
                        drawSimpleDateLegend(g2, (int) (area.getCenterX() - 170), (int) (area.getCenterY() + 7),
                                dataTable, colorColumn, minColor, maxColor);
                        return new BlockResult();
                    } else {
                        final String minColorString = Tools.formatNumber(minColor);
                        final String maxColorString = Tools.formatNumber(maxColor);
                        drawSimpleNumericalLegend(g2, (int) (area.getCenterX() - 75),
                                (int) (area.getCenterY() + 7), getDataTable().getColumnName(colorColumn),
                                minColorString, maxColorString);
                        return new BlockResult();
                    }
                }

                @Override
                public void draw(java.awt.Graphics2D g2, java.awt.geom.Rectangle2D area) {
                    draw(g2, area, null);
                }

            };

            BlockContainer wrapper = new BlockContainer(new BorderArrangement());

            LabelBlock title = new LabelBlock(getDataTable().getColumnName(colorColumn),
                    new Font("SansSerif", Font.BOLD, 12));
            title.setPadding(0, 5, 5, 5);
            wrapper.add(title, RectangleEdge.LEFT);

            BlockContainer items = legendTitle.getItemContainer();
            wrapper.add(items, RectangleEdge.RIGHT);

            legendTitle.setWrapper(wrapper);

            chart.addLegend(legendTitle);
        }
    } else {
        chart = ChartFactory.createScatterPlot(null, // chart title
                null, // domain axis label
                null, // range axis label
                dataSet, // data
                PlotOrientation.VERTICAL, // orientation
                false, // include legend
                true, // tooltips
                false // URLs
        );
    }

    // GENERAL CHART SETTINGS

    // set the background colors for the chart...
    chart.setBackgroundPaint(Color.WHITE);
    chart.getPlot().setBackgroundPaint(Color.WHITE);
    chart.setAntiAlias(false);

    // general plot settings
    XYPlot plot = chart.getXYPlot();
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // domain axis
    if (axis[X_AXIS] >= 0) {
        if (dataTable.isNominal(axis[X_AXIS])) {
            String[] values = new String[dataTable.getNumberOfValues(axis[X_AXIS])];
            for (int i = 0; i < values.length; i++) {
                values[i] = dataTable.mapIndex(axis[X_AXIS], i);
            }
            plot.setDomainAxis(new SymbolAxis(dataTable.getColumnName(axis[X_AXIS]), values));
        } else if (dataTable.isDate(axis[X_AXIS]) || dataTable.isDateTime(axis[X_AXIS])) {
            DateAxis domainAxis = new DateAxis(dataTable.getColumnName(axis[X_AXIS]));
            domainAxis.setTimeZone(Tools.getPreferredTimeZone());
            plot.setDomainAxis(domainAxis);
        } else {
            if (logScales[X_AXIS]) {
                LogAxis domainAxis = new LogAxis(dataTable.getColumnName(axis[X_AXIS]));
                domainAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits(Locale.US));
                plot.setDomainAxis(domainAxis);
            } else {
                NumberAxis domainAxis = new NumberAxis(dataTable.getColumnName(axis[X_AXIS]));
                domainAxis.setAutoRangeStickyZero(false);
                domainAxis.setAutoRangeIncludesZero(false);
                plot.setDomainAxis(domainAxis);
            }
        }
    }

    if (axis[X_AXIS] >= 0) {
        Range range = getRangeForDimension(axis[X_AXIS]);
        if (range != null) {
            plot.getDomainAxis().setRange(range, true, false);
        } else {
            plot.getDomainAxis().setAutoRange(true);
        }
    }

    plot.getDomainAxis().setLabelFont(LABEL_FONT_BOLD);
    plot.getDomainAxis().setTickLabelFont(LABEL_FONT);

    // rotate labels
    if (isLabelRotating()) {
        plot.getDomainAxis().setTickLabelsVisible(true);
        plot.getDomainAxis().setVerticalTickLabels(true);
    }

    // range axis
    if (axis[Y_AXIS] >= 0) {
        if (dataTable.isNominal(axis[Y_AXIS])) {
            String[] values = new String[dataTable.getNumberOfValues(axis[Y_AXIS])];
            for (int i = 0; i < values.length; i++) {
                values[i] = dataTable.mapIndex(axis[Y_AXIS], i);
            }
            plot.setRangeAxis(new SymbolAxis(dataTable.getColumnName(axis[Y_AXIS]), values));
        } else if (dataTable.isDate(axis[Y_AXIS]) || dataTable.isDateTime(axis[Y_AXIS])) {
            DateAxis rangeAxis = new DateAxis(dataTable.getColumnName(axis[Y_AXIS]));
            rangeAxis.setTimeZone(Tools.getPreferredTimeZone());
            plot.setRangeAxis(rangeAxis);
        } else {
            if (logScales[Y_AXIS]) {
                LogAxis rangeAxis = new LogAxis(dataTable.getColumnName(axis[Y_AXIS]));
                rangeAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits(Locale.US));
                plot.setRangeAxis(rangeAxis);
            } else {
                NumberAxis rangeAxis = new NumberAxis(dataTable.getColumnName(axis[Y_AXIS]));
                rangeAxis.setAutoRangeStickyZero(false);
                rangeAxis.setAutoRangeIncludesZero(false);
                plot.setRangeAxis(rangeAxis);
            }
        }
    }
    plot.getRangeAxis().setLabelFont(LABEL_FONT_BOLD);
    plot.getRangeAxis().setTickLabelFont(LABEL_FONT);

    if (axis[Y_AXIS] >= 0) {
        Range range = getRangeForDimension(axis[Y_AXIS]);
        if (range != null) {
            plot.getRangeAxis().setRange(range, true, false);
        } else {
            plot.getRangeAxis().setAutoRange(true);
        }
    }

    // Chart Panel Settings
    AbstractChartPanel panel = getPlotterPanel();
    if (panel == null) {
        panel = createPanel(chart);

        // react to mouse clicks
        panel.addChartMouseListener(new ChartMouseListener() {

            @Override
            public void chartMouseClicked(ChartMouseEvent e) {
                if (e.getTrigger().getClickCount() > 1) {
                    if (e.getEntity() instanceof XYItemEntity) {
                        XYItemEntity entity = (XYItemEntity) e.getEntity();
                        if (entity != null) {
                            String id = idMap.get(new SeriesAndItem(entity.getSeriesIndex(), entity.getItem()));
                            if (id != null) {
                                ObjectVisualizer visualizer = ObjectVisualizerService
                                        .getVisualizerForObject(dataTable);
                                visualizer.startVisualization(id);
                            }
                        }
                    }
                }
            }

            @Override
            public void chartMouseMoved(ChartMouseEvent e) {
            }
        });

    } else {
        panel.setChart(chart);
    }

    // tooltips
    class CustomXYToolTipGenerator implements XYToolTipGenerator {

        public CustomXYToolTipGenerator() {
        }

        private String formatValue(int axis, double value) {
            if (dataTable.isNominal(axis)) {
                // TODO add mapping of value to nominal value
                return Tools.formatIntegerIfPossible(value);
            } else if (dataTable.isNumerical(axis)) {
                return Tools.formatIntegerIfPossible(value);
            } else if (dataTable.isDate(axis)) {
                return Tools.createDateAndFormat(value);
            } else if (dataTable.isTime(axis)) {
                return Tools.createTimeAndFormat(value);
            } else if (dataTable.isDateTime(axis)) {
                return Tools.createDateTimeAndFormat(value);
            }
            return "?";
        }

        @Override
        public String generateToolTip(XYDataset dataset, int row, int column) {
            String id = idMap.get(new SeriesAndItem(row, column));
            if (id != null) {
                return "<html><b>Id: " + id + "</b> (" + dataset.getSeriesKey(row) + ", "
                        + formatValue(axis[X_AXIS], dataset.getXValue(row, column)) + ", "
                        + formatValue(axis[Y_AXIS], dataset.getYValue(row, column)) + ")</html>";

            } else {
                return "<html>(" + dataset.getSeriesKey(row) + ", "
                        + formatValue(axis[X_AXIS], dataset.getXValue(row, column)) + ", "
                        + formatValue(axis[Y_AXIS], dataset.getYValue(row, column)) + ")</html>";
            }
        }
    }

    for (int i = 0; i < dataSet.getSeriesCount(); i++) {
        plot.getRenderer().setSeriesToolTipGenerator(i, new CustomXYToolTipGenerator());
    }
}

From source file:edu.jhuapl.graphs.jfreechart.JFreeChartTimeSeriesGraphSource.java

/**
 * Initializes the graph.  This method generates the backing {@link JFreeChart} from the time series and graph
 * parameter data./*from  w w w. j  a  va 2s. c  o  m*/
 *
 * @throws GraphException if the initialization fails
 */
public void initialize() throws GraphException {
    String title = getParam(GraphSource.GRAPH_TITLE, String.class, DEFAULT_TITLE);
    String xLabel = getParam(GraphSource.GRAPH_X_LABEL, String.class, DEFAULT_DOMAIN_LABEL);
    String yLabel = getParam(GraphSource.GRAPH_Y_LABEL, String.class, DEFAULT_RANGE_LABEL);
    Shape graphShape = getParam(GraphSource.GRAPH_SHAPE, Shape.class, DEFAULT_GRAPH_SHAPE);
    Paint graphColor = getParam(GraphSource.GRAPH_COLOR, Paint.class, DEFAULT_GRAPH_COLOR);
    boolean legend = getParam(GraphSource.GRAPH_LEGEND, Boolean.class, DEFAULT_GRAPH_LEGEND);
    boolean graphToolTip = getParam(GraphSource.GRAPH_TOOL_TIP, Boolean.class, DEFAULT_GRAPH_TOOL_TIP);
    Stroke graphStroke = getParam(GraphSource.GRAPH_STROKE, Stroke.class, DEFAULT_GRAPH_STROKE);
    Font titleFont = getParam(GraphSource.GRAPH_FONT, Font.class, DEFAULT_GRAPH_TITLE_FONT);
    boolean graphBorder = getParam(GraphSource.GRAPH_BORDER, Boolean.class, DEFAULT_GRAPH_BORDER);
    boolean legendBorder = getParam(GraphSource.LEGEND_BORDER, Boolean.class, DEFAULT_LEGEND_BORDER);
    Double offset = getParam(GraphSource.AXIS_OFFSET, Double.class, DEFAULT_AXIS_OFFSET);

    checkSeriesType(data);
    @SuppressWarnings("unchecked")
    List<? extends TimeSeriesInterface> timeData = (List<? extends TimeSeriesInterface>) data;

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    int seriesCount = 1;
    for (TimeSeriesInterface series : timeData) {
        dataset.addSeries(buildTimeSeries(series, seriesCount));
        seriesCount += 1;
    }

    // actually create the chart
    this.chart = ChartFactory.createTimeSeriesChart(title, xLabel, yLabel, dataset, false, graphToolTip, false);

    // start customizing it
    Paint backgroundColor = getParam(GraphSource.BACKGROUND_COLOR, Paint.class, DEFAULT_BACKGROUND_COLOR);
    Paint plotColor = getParam(JFreeChartTimeSeriesGraphSource.PLOT_COLOR, Paint.class, backgroundColor);
    Paint graphDomainGridlinePaint = getParam(GraphSource.GRAPH_DOMAIN_GRIDLINE_PAINT, Paint.class,
            backgroundColor);
    Paint graphRangeGridlinePaint = getParam(GraphSource.GRAPH_RANGE_GRIDLINE_PAINT, Paint.class,
            backgroundColor);

    this.chart.setBackgroundPaint(backgroundColor);
    XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(plotColor);
    plot.setAxisOffset(new RectangleInsets(offset, offset, offset, offset));
    plot.setDomainGridlinePaint(graphDomainGridlinePaint);
    plot.setRangeGridlinePaint(graphRangeGridlinePaint);

    if (graphBorder) {

    } else {
        plot.setOutlinePaint(null);
    }

    //Use a TextTitle to change the font of the graph title
    TextTitle title1 = new TextTitle();
    title1.setText(title);
    title1.setFont(titleFont);
    chart.setTitle(title1);

    //Makes a wrapper for the legend to remove the border around it
    if (legend) {
        LegendTitle legend1 = new LegendTitle(chart.getPlot());
        BlockContainer wrapper = new BlockContainer(new BorderArrangement());
        if (legendBorder) {
            wrapper.setFrame(new BlockBorder(1, 1, 1, 1));
        } else {
            wrapper.setFrame(new BlockBorder(0, 0, 0, 0));
        }
        BlockContainer items = legend1.getItemContainer();
        items.setPadding(2, 10, 5, 2);
        wrapper.add(items);
        legend1.setWrapper(wrapper);
        legend1.setPosition(RectangleEdge.BOTTOM);
        legend1.setHorizontalAlignment(HorizontalAlignment.CENTER);

        if (params.get(GraphSource.LEGEND_FONT) instanceof Font) {
            legend1.setItemFont(((Font) params.get(GraphSource.LEGEND_FONT)));
        }

        chart.addSubtitle(legend1);
    }

    boolean include0 = getParam(GraphSource.GRAPH_RANGE_INCLUDE_0, Boolean.class, true);
    NumberAxis numAxis = (NumberAxis) plot.getRangeAxis();
    double rangeLower = getParam(GraphSource.GRAPH_RANGE_LOWER_BOUND, Double.class, numAxis.getLowerBound());
    double rangeUpper = getParam(GraphSource.GRAPH_RANGE_UPPER_BOUND, Double.class, numAxis.getUpperBound());
    boolean graphRangeIntegerTick = getParam(GraphSource.GRAPH_RANGE_INTEGER_TICK, Boolean.class, false);
    boolean graphRangeMinorTickVisible = getParam(GraphSource.GRAPH_RANGE_MINOR_TICK_VISIBLE, Boolean.class,
            true);

    if (include0) {
        rangeLower = 0;
    }

    numAxis.setRange(rangeLower, rangeUpper);

    if (graphRangeIntegerTick) {
        numAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    numAxis.setMinorTickMarksVisible(graphRangeMinorTickVisible);
    setupFont(numAxis, GraphSource.GRAPH_Y_AXIS_FONT);

    if (params.get(GraphSource.GRAPH_Y_AXIS_LABEL_FONT) instanceof Font) {
        numAxis.setLabelFont(((Font) params.get(GraphSource.GRAPH_Y_AXIS_LABEL_FONT)));
    }

    TimeResolution minimumResolution = getMinimumResolution(timeData);
    DateFormat dateFormat = getParam(GraphSource.GRAPH_DATE_FORMATTER, DateFormat.class,
            new DefaultDateFormatFactory().getFormat(minimumResolution));

    if (params.get(DATE_AXIS) instanceof DateAxis) {
        DateAxis dateAxis = (DateAxis) params.get(DATE_AXIS);
        dateAxis.setLabel(xLabel);
        plot.setDomainAxis(dateAxis);
    }
    DateAxis dateAxis = ((DateAxis) plot.getDomainAxis());
    dateAxis.setDateFormatOverride(dateFormat);

    if (params.get(GraphSource.GRAPH_X_AXIS_LABEL_FONT) instanceof Font) {
        dateAxis.setLabelFont(((Font) params.get(GraphSource.GRAPH_X_AXIS_LABEL_FONT)));
    }

    int minTick = getParam(GraphSource.GRAPH_MIN_DOMAIN_TICK, Integer.class, 1);
    if (minTick <= 0) {
        minTick = 1;
    }

    dateAxis.setTickUnit(getDateTickUnit(minimumResolution, minTick), false, false);
    //dateAxis.setMinorTickMarksVisible(true);
    //dateAxis.setMinorTickCount(7);
    dateAxis.setMinorTickMarkOutsideLength(2);

    Integer minorTick = getParam(GraphSource.GRAPH_MINOR_TICKS, Integer.class, null);
    if (minorTick != null) {
        int minorVal = minorTick;
        if (minorVal > 0) {
            dateAxis.setMinorTickCount(minorVal);
        }
    }

    setupFont(dateAxis, GraphSource.GRAPH_X_AXIS_FONT);

    //double lowerMargin = getParam(DOMAIN_AXIS_LOWER_MARGIN, Double.class, DEFAULT_DOMAIN_AXIS_LOWER_MARGIN);
    double lowerMargin = getParam(DOMAIN_AXIS_LOWER_MARGIN, Double.class, DEFAULT_DOMAIN_AXIS_LOWER_MARGIN);
    dateAxis.setLowerMargin(lowerMargin);

    //double upperMargin = getParam(DOMAIN_AXIS_UPPER_MARGIN, Double.class, DEFAULT_DOMAIN_AXIS_UPPER_MARGIN);
    double upperMargin = getParam(DOMAIN_AXIS_UPPER_MARGIN, Double.class, DEFAULT_DOMAIN_AXIS_UPPER_MARGIN);
    dateAxis.setUpperMargin(upperMargin);

    Date domainLower = getParam(GraphSource.GRAPH_DOMAIN_LOWER_BOUND, Date.class, dateAxis.getMinimumDate());
    Date domainUpper = getParam(GraphSource.GRAPH_DOMAIN_UPPER_BOUND, Date.class, dateAxis.getMaximumDate());

    dateAxis.setRange(domainLower, domainUpper);

    // depending on the domain axis range, display either 1 tick per day, week, month or year
    TickUnits standardUnits = new TickUnits();
    standardUnits.add(new DateTickUnit(DateTickUnitType.DAY, 1));
    standardUnits.add(new DateTickUnit(DateTickUnitType.DAY, 7));
    standardUnits.add(new DateTickUnit(DateTickUnitType.MONTH, 1));
    standardUnits.add(new DateTickUnit(DateTickUnitType.YEAR, 1));
    dateAxis.setStandardTickUnits(standardUnits);

    TimeSeriesRenderer renderer = new TimeSeriesRenderer(dataset);
    setupRenderer(renderer, graphColor, graphShape, graphStroke);
    renderer.setBaseFillPaint(Color.BLACK);
    renderer.setSeriesOutlinePaint(0, Color.WHITE);

    //renderer.setUseOutlinePaint(true);

    plot.setRenderer(renderer);
    this.initialized = true;
}

From source file:mil.tatrc.physiology.utilities.csv.plots.ActionEventPlotter.java

public void createGraph(PlotJob job, List<List<Double>> timeData, List<List<Double>> data,
        List<LogEvent> events, List<SEAction> actions) {
    CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions
    String title = job.name + "_";
    XYSeriesCollection dataSet = new XYSeriesCollection();
    double maxY = 0;
    double minY = Double.MAX_VALUE;
    for (int i = 0; i < timeData.size(); i++) {
        if (timeData.get(i) == null || data.get(i) == null) {
            job.bgColor = Color.white; //This hits when we have Expected data but NOT computed data
            continue;
        }/* w ww  . ja v  a2  s .  c o  m*/

        title = title + job.headers.get(i) + "_";
        XYSeries dataSeries;
        if (job.isComparePlot) {
            if (timeData.size() > 1)
                dataSeries = plotTool.createXYSeries(i == 0 ? "Expected" : "Computed", timeData.get(i),
                        data.get(i));
            else //If we're comparing but only have one data list, expected is missing, so rename to computed
            {
                dataSeries = plotTool.createXYSeries("Computed", timeData.get(i), data.get(i));
            }
        } else
            dataSeries = plotTool.createXYSeries(job.headers.get(i), timeData.get(i), data.get(i));
        dataSet.addSeries(dataSeries);
        maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY;
        minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY;
    }
    title = title + "vs_Time_Action_Event_Plot";

    //Override the constructed title if desired (usually for compare plots)
    if (job.titleOverride != null && !job.titleOverride.isEmpty()
            && !job.titleOverride.equalsIgnoreCase("None"))
        title = job.titleOverride;

    double rangeLength = maxY - minY;
    if (Math.abs(rangeLength) < 1e-6) {
        rangeLength = .01;
    }

    class AEEntry implements Comparable<AEEntry> {
        public String name;
        public List<Double> times = new ArrayList<Double>();
        public List<Double> YVals = new ArrayList<Double>();
        public String type = "";

        public int compareTo(AEEntry entry) {
            return times.get(0) < entry.times.get(0) ? -1 : times.get(0) > entry.times.get(0) ? 1 : 0;
        }
    }

    List<AEEntry> allActionsAndEvents = new ArrayList<AEEntry>();

    if (!job.skipAllEvents) {
        //Make points for each event
        //Treat each event like two points on the same vertical line
        for (LogEvent event : events) {
            boolean skip = false;

            for (String eventToSkip : job.eventOmissions) {
                if (event.text.contains(eventToSkip))
                    skip = true;
            }
            if (skip)
                continue;
            AEEntry entry = new AEEntry();

            entry.times.add(event.time.getValue());
            if (job.logAxis)
                entry.YVals.add(maxY);
            else if (job.forceZeroYAxisBound && maxY < 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(maxY + 0.15 * rangeLength);

            entry.times.add(event.time.getValue());
            if (job.logAxis)
                entry.YVals.add(minY);
            else if (job.forceZeroYAxisBound && minY > 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(minY - 0.15 * rangeLength);

            entry.name = event.text + "\r\nt=" + event.time.getValue();
            entry.type = "EVENT:";

            allActionsAndEvents.add(entry);
        }
    }

    if (!job.skipAllActions) {
        //Make similar entries for actions
        for (SEAction action : actions) {
            boolean skip = false;

            for (String actionToSkip : job.actionOmissions) {
                if (action.toString().contains(actionToSkip))
                    skip = true;
            }
            if (skip)
                continue;

            if (action.toString().contains("Advance Time"))
                continue;

            AEEntry entry = new AEEntry();

            entry.times.add(action.getScenarioTime().getValue());
            if (job.logAxis)
                entry.YVals.add(maxY);
            else if (job.forceZeroYAxisBound && maxY < 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(maxY + 0.15 * rangeLength);

            entry.times.add(action.getScenarioTime().getValue());
            if (job.logAxis)
                entry.YVals.add(minY);
            else if (job.forceZeroYAxisBound && minY > 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(minY - 0.15 * rangeLength);

            entry.name = action.toString() + "\r\nt=" + action.getScenarioTime().getValue();
            entry.type = "ACTION:";

            allActionsAndEvents.add(entry);
        }
    }

    //Sort the list
    Collections.sort(allActionsAndEvents);

    //Add a series for each entry
    for (AEEntry entry : allActionsAndEvents) {
        dataSet.addSeries(plotTool.createXYSeries(entry.type + entry.name, entry.times, entry.YVals));
    }

    //If we have experimental data, try to load it and create a dataset for it
    XYSeriesCollection expDataSet = new XYSeriesCollection();
    if (job.experimentalData != null && !job.experimentalData.isEmpty()) {
        Map<String, List<Double>> expData = new HashMap<String, List<Double>>();
        List<String> expHeaders = new ArrayList<String>();

        try {
            CSVContents csv = new CSVContents(job.experimentalData);
            csv.abbreviateContents = 0;
            csv.readAll(expData);
            expHeaders = csv.getHeaders();
        } catch (Exception e) {
            Log.error("Unable to read experimental data");
        }

        if (!expData.isEmpty() && !expHeaders.isEmpty()) {
            List<Double> expTimeData = new ArrayList<Double>();
            expTimeData = expData.get("Time(s)");

            for (String h : expHeaders) //Will assume all headers from exp file will be on same Y axis vs time
            {
                if (h.equalsIgnoreCase("Time(s)"))
                    continue;

                expDataSet.addSeries(plotTool.createXYSeries("Experimental " + h, expTimeData, expData.get(h)));
            }
        }
    }

    //set labels
    String XAxisLabel = "Time(s)";
    String YAxisLabel = job.headers.get(0);

    JFreeChart chart = ChartFactory.createXYLineChart(
            job.titleOverride != null && job.titleOverride.equalsIgnoreCase("None") ? "" : title, // chart title
            XAxisLabel, // x axis label
            YAxisLabel, // y axis label
            dataSet, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    Log.info("Creating Graph " + title);
    XYPlot plot = (XYPlot) chart.getPlot();

    if (!job.logAxis) {
        // Determine Y range
        double resMax0 = maxY;
        double resMin0 = minY;
        if (Double.isNaN(resMax0) || Double.isNaN(resMin0))
            plot.getDomainAxis().setLabel("Range is NaN");
        if (DoubleUtils.isZero(resMin0))
            resMin0 = -0.000001;
        if (DoubleUtils.isZero(resMax0))
            resMax0 = 0.000001;
        if (job.forceZeroYAxisBound && resMin0 >= 0)
            resMin0 = -.000001;
        if (job.forceZeroYAxisBound && resMax0 <= 0)
            resMax0 = .000001;
        rangeLength = resMax0 - resMin0;
        ValueAxis yAxis = plot.getRangeAxis();
        if (rangeLength != 0)
            yAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);//15% buffer so we can see top and bottom clearly           

        //Add another Y axis to the right side for easier reading
        ValueAxis rightYAxis = new NumberAxis();
        rightYAxis.setRange(yAxis.getRange());
        rightYAxis.setLabel("");

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null) {
                yAxis.setLowerBound(job.Y1LowerBound);
                rightYAxis.setLowerBound(job.Y1LowerBound);
            }
            if (job.Y1UpperBound != null) {
                yAxis.setUpperBound(job.Y1UpperBound);
                rightYAxis.setUpperBound(job.Y1UpperBound);
            }
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }
        plot.setRangeAxis(0, yAxis);
        plot.setRangeAxis(1, rightYAxis);

    } else {
        double resMin = minY;
        double resMax = maxY;
        if (resMin <= 0.0)
            resMin = .00001;
        LogarithmicAxis yAxis = new LogarithmicAxis("Log(" + YAxisLabel + ")");
        LogarithmicAxis rightYAxis = new LogarithmicAxis("");
        yAxis.setLowerBound(resMin);
        rightYAxis.setLowerBound(resMin);
        yAxis.setUpperBound(resMax);
        rightYAxis.setUpperBound(resMax);

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null) {
                yAxis.setLowerBound(job.Y1LowerBound);
                rightYAxis.setLowerBound(job.Y1LowerBound);
            }
            if (job.Y1UpperBound != null) {
                yAxis.setUpperBound(job.Y1UpperBound);
                rightYAxis.setUpperBound(job.Y1UpperBound);
            }
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }
        plot.setRangeAxis(0, yAxis);
        plot.setRangeAxis(1, rightYAxis);
    }

    //Override X bounds if desired
    try {
        if (job.X1LowerBound != null)
            plot.getDomainAxis(0).setLowerBound(job.X1LowerBound);
        if (job.X1UpperBound != null)
            plot.getDomainAxis(0).setUpperBound(job.X1UpperBound);
    } catch (Exception e) {
        Log.error("Couldn't set X bounds. You probably tried to set a bound on an axis that doesn't exist.");
    }

    //Override labels if desired
    if (job.X1Label != null && !plot.getDomainAxis(0).getLabel().contains("NaN"))
        plot.getDomainAxis(0).setLabel(job.X1Label.equalsIgnoreCase("None") ? "" : job.X1Label);
    if (job.Y1Label != null)
        plot.getRangeAxis(0).setLabel(job.Y1Label.equalsIgnoreCase("None") ? "" : job.Y1Label);

    //If we have experimental data, set up the renderer for it and add to plot
    if (expDataSet.getSeriesCount() != 0) {
        XYItemRenderer renderer1 = new XYLineAndShapeRenderer(false, true); // Shapes only
        renderer1.setSeriesShape(0, ShapeUtilities.createDiamond(8));
        plot.setDataset(1, expDataSet);
        plot.setRenderer(1, renderer1);
        plot.mapDatasetToDomainAxis(1, 0);
        plot.mapDatasetToRangeAxis(1, 0);
    }

    formatAEPlot(job, chart);
    plot.setDomainGridlinesVisible(job.showGridLines);
    plot.setRangeGridlinesVisible(job.showGridLines);

    //Changing line widths and colors
    XYItemRenderer r = plot.getRenderer();
    BasicStroke wideLine = new BasicStroke(2.0f);
    Color[] AEcolors = { Color.red, Color.green, Color.black, Color.magenta, Color.orange };
    Color[] dataColors = { Color.blue, Color.cyan, Color.gray, Color.black, Color.red };
    for (int i = 0, cIndex = 0; i < dataSet.getSeriesCount(); i++, cIndex++) {
        r.setSeriesStroke(i, wideLine);
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
        renderer.setBaseShapesVisible(false);
        if (cIndex > 4)
            cIndex = 0;
        if (i < job.headers.size()) //Our actual data
        {
            renderer.setSeriesFillPaint(i, dataColors[cIndex]);
            renderer.setSeriesPaint(i, dataColors[cIndex]);
        } else //actions and events in procession of other colors
        {
            renderer.setSeriesFillPaint(i, AEcolors[cIndex]);
            renderer.setSeriesPaint(i, AEcolors[cIndex]);
        }
    }
    //Special color and format changes for compare plots
    if (job.isComparePlot) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();

        for (int i = 0; i < dataSet.getSeriesCount(); i++) {
            if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Expected")) {
                renderer.setSeriesStroke(//makes a dashed line
                        i, //argument below float[]{I,K} -> alternates between solid and opaque (solid for I, opaque for K)
                        new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f,
                                new float[] { 15.0f, 30.0f }, 0.0f));
                renderer.setDrawSeriesLineAsPath(true);
                renderer.setUseFillPaint(true);
                renderer.setBaseShapesVisible(false);
                renderer.setSeriesFillPaint(i, Color.black);
                renderer.setSeriesPaint(i, Color.black);
            }
            if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Computed")) {
                renderer.setSeriesFillPaint(i, Color.red);
                renderer.setSeriesPaint(i, Color.red);
            }
            if (dataSet.getSeries(i).getKey().toString().startsWith("ACTION")) {
                renderer.setSeriesFillPaint(i, Color.green);
                renderer.setSeriesPaint(i, Color.green);
            }
            if (dataSet.getSeries(i).getKey().toString().startsWith("EVENT")) {
                renderer.setSeriesFillPaint(i, Color.blue);
                renderer.setSeriesPaint(i, Color.blue);
            }
        }
    }

    //Split the auto-generated legend into two legends, one for data and one for actions and events
    LegendItemCollection originalLegendCollection = plot.getLegendItems();
    final LegendItemCollection dataLegendCollection = new LegendItemCollection();
    int i;
    for (i = 0; i < job.headers.size() && i < originalLegendCollection.getItemCount(); i++) {
        if (originalLegendCollection.get(i).getLabel().startsWith("ACTION")
                || originalLegendCollection.get(i).getLabel().startsWith("EVENT"))
            break;
        dataLegendCollection.add(originalLegendCollection.get(i));
    }
    final LegendItemCollection remainingLegendCollection = new LegendItemCollection();
    for (; i < originalLegendCollection.getItemCount(); i++) {
        remainingLegendCollection.add(originalLegendCollection.get(i));
    }
    chart.removeLegend();
    LegendItemSource source = new LegendItemSource() {
        LegendItemCollection lic = new LegendItemCollection();
        {
            lic.addAll(dataLegendCollection);
        }

        public LegendItemCollection getLegendItems() {
            return lic;
        }
    };
    LegendTitle dataLegend = new LegendTitle(source);
    dataLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));
    dataLegend.setBorder(2, 2, 2, 2);
    dataLegend.setBackgroundPaint(Color.white);
    dataLegend.setPosition(RectangleEdge.TOP);
    dataLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22));
    chart.addLegend(dataLegend);

    source = new LegendItemSource() {
        LegendItemCollection lic = new LegendItemCollection();
        {
            lic.addAll(remainingLegendCollection);
        }

        public LegendItemCollection getLegendItems() {
            return lic;
        }
    };
    LegendTitle actionEventsLegend = new LegendTitle(source);
    actionEventsLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));
    actionEventsLegend.setBorder(2, 2, 2, 2);
    actionEventsLegend.setBackgroundPaint(Color.white);
    actionEventsLegend.setPosition(RectangleEdge.BOTTOM);
    actionEventsLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22));
    if (!job.hideAELegend && !job.removeAllLegends)
        chart.addLegend(actionEventsLegend);

    if (job.removeAllLegends)
        chart.removeLegend();

    int verticalPixels = 800 + 170 * (allActionsAndEvents.size() / 5);

    //This is a little hacky, but if we want only the legend, just extend Plot() and remove the draw functionality so it makes a blank plot
    class legendPlot extends Plot {
        public void draw(Graphics2D arg0, Rectangle2D arg1, Point2D arg2, PlotState arg3,
                PlotRenderingInfo arg4) {

        }

        public String getPlotType() {
            return null;
        }
    }
    //Then add the legend to that and throw away the original plot
    if (job.legendOnly) {
        chart = new JFreeChart("", null, new legendPlot(), false);
        chart.addLegend(actionEventsLegend);
    }

    try {
        FileUtils.createDirectory(job.outputDir);
        String filename = job.outputFilename == null
                ? job.outputDir + "/" + plotTool.MakeFileName(title) + ".jpg"
                : job.outputDir + "/" + job.outputFilename;
        if (!filename.endsWith(".jpg"))
            filename = filename + ".jpg";
        File JPGFile = new File(filename);
        if (job.imageHeight != null && job.imageWidth != null)
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, job.imageWidth, job.imageHeight);
        else if (!job.hideAELegend && !job.removeAllLegends)
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, verticalPixels);
        else
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800);
    } catch (IOException e) {
        Log.error(e.getMessage());
    }
}

From source file:org.gumtree.vis.plot1d.Plot1D.java

private void createChart() {

    String title = null;//from  w  w  w .  j ava2 s  . c  om
    String xTitle = null;
    String yTitle = null;
    if (dataset != null) {
        title = dataset.getTitle();
        xTitle = dataset.getXTitle() + (dataset.getXUnits() == null ? "" : " (" + dataset.getXUnits() + ")");
        yTitle = dataset.getYTitle() + (dataset.getYUnits() == null ? "" : " (" + dataset.getYUnits() + ")");
    } else {
        dataset = new XYErrorDataset();
    }
    chart = createXYLineChart(title, xTitle, yTitle, dataset, PlotOrientation.VERTICAL, true, false, true);
    chart.setBackgroundPaint(Color.WHITE);
    final LegendTitle legend = (LegendTitle) chart.getLegend();
    RectangleEdge legendPosition = RectangleEdge.BOTTOM;
    try {
        String legendProperty = "RectangleEdge." + System.getProperty("kuranda1D.legendPosition");
        if (RectangleEdge.BOTTOM.toString().equals(legendProperty))
            legendPosition = RectangleEdge.BOTTOM;
        else if (RectangleEdge.RIGHT.toString().equals(legendProperty))
            legendPosition = RectangleEdge.RIGHT;
        else if (RectangleEdge.LEFT.toString().equals(legendProperty))
            legendPosition = RectangleEdge.LEFT;
        else if (RectangleEdge.TOP.toString().equals(legendProperty))
            legendPosition = RectangleEdge.TOP;
    } catch (Exception e) {
        // TODO: handle exception
    }
    legend.setPosition(legendPosition);
    chart.setBorderVisible(true);
    //      ChartUtilities.applyCurrentTheme(chart);
    //      chartTheme.apply(chart);

    XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setDomainPannable(true);
    plot.setRangePannable(true);

    plot.setDomainGridlinesVisible(true);
    //        plot.setDomainCrosshairLockedOnData(true);
    //        plot.setDomainCrosshairVisible(true);
    plot.setRangeGridlinesVisible(true);
    //        plot.setRangeCrosshairLockedOnData(true);
    //        plot.setRangeCrosshairVisible(true);

    xAxis = plot.getDomainAxis();
    yAxis = plot.getRangeAxis();

    plot.setDataset(dataset);
    XYItemRenderer renderer = chart.getXYPlot().getRenderer();
    if (renderer instanceof XYLineAndShapeRenderer) {
        //         ((XYLineAndShapeRenderer) renderer).setBaseShapesVisible(true);
        ((XYLineAndShapeRenderer) renderer).setBaseShapesFilled(true);
    }
    //      XYErrorRenderer errorRenderer = (XYErrorRenderer) chart.getXYPlot().getRenderer();
    //      errorRenderer.setDrawXError(true);
    //        StandardXYItemRenderer renderer = (StandardXYItemRenderer) plot.getRenderer();
    //        renderer.setPlotLines(true);
    //        renderer.setBaseShapesVisible(true);

    chart.fireChartChanged();
}

From source file:cs.stats.gui.StatsCharts.java

private ChartPanel createChart(String axisLabel, int type) {
    int width = (screenSize.width - (screenSize.width / 35));
    int height = (int) (screenSize.height - (screenSize.height / (double) 4));

    //int width = (screenSize.width - (screenSize.width / 35)) / 2;
    //int height = (int) (screenSize.height - (screenSize.height / (double) 4)) / 2;

    lastValue = new double[SUBPLOT_COUNT];
    //================= visualise standard chart ==========================
    CombinedDomainXYPlot combineddomainxyplot = new CombinedDomainXYPlot(new DateAxis("Time"));

    lastValue[0] = 100D;/*from  ww w .  j a  v  a 2s. c  om*/
    TimeSeries timeseries = null;
    XYPlot xyplot = null;

    //add new timeseries to modularity row
    datasets[type] = new TimeSeriesCollection();

    NumberAxis numberaxis = new NumberAxis(axisLabel);
    numberaxis.setAutoRangeIncludesZero(true);

    //fast
    StandardXYItemRenderer xyItemRender = new StandardXYItemRenderer();
    //original
    //xyItemRender = new StandardXYItemRenderer();

    xyItemRender.setSeriesStroke(0,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));
    xyItemRender.setSeriesStroke(1,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));
    xyItemRender.setSeriesStroke(2,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));
    xyItemRender.setSeriesStroke(3,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));
    xyItemRender.setSeriesStroke(4,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));
    xyItemRender.setSeriesStroke(5,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));
    xyItemRender.setSeriesStroke(6,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));
    xyItemRender.setSeriesStroke(7,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));
    xyItemRender.setSeriesStroke(8,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));
    xyItemRender.setSeriesStroke(9,
            new BasicStroke(lineThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, null, 0));

    //TODO colours need to be defined statically before the renderer is created!
    xyplot = new XYPlot(datasets[type], null, numberaxis, xyItemRender);

    switch (type) {
    case 0: {
        xyItemRender.setSeriesPaint(0, Color.BLACK);
        timeseries = new TimeSeries("Reply rate 1.0", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(1, Color.BLUE);
        timeseries = new TimeSeries("Reply rate 0.9", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(2, Color.ORANGE);
        timeseries = new TimeSeries("Reply rate 0.8", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(3, Color.GREEN);
        timeseries = new TimeSeries("Reply rate 0.7", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(4, Color.MAGENTA);
        timeseries = new TimeSeries("Reply rate 0.6", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(5, Color.LIGHT_GRAY);
        timeseries = new TimeSeries("Reply rate 0.5", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(6, Color.YELLOW);
        timeseries = new TimeSeries("Reply rate 0.4", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        //            xyItemRender.setSeriesPaint(7, Color.PINK);
        //            timeseries = new TimeSeries("Reply rate 0.3", org.jfree.data.time.Hour.class);
        //            datasets[type].addSeries(timeseries);
        //
        //            xyItemRender.setSeriesPaint(8, Color.RED);
        //            timeseries = new TimeSeries("Reply rate 0.2", org.jfree.data.time.Hour.class);
        //            datasets[type].addSeries(timeseries);
        //
        //            xyItemRender.setSeriesPaint(9, Color.CYAN);
        //            timeseries = new TimeSeries("Reply rate 0.1", org.jfree.data.time.Hour.class);
        //            datasets[type].addSeries(timeseries);
    }
        break;
    case 1: {
        xyItemRender.setSeriesPaint(0, Color.BLACK);
        timeseries = new TimeSeries("0% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(1, Color.BLUE);
        timeseries = new TimeSeries("1% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(2, Color.ORANGE);
        timeseries = new TimeSeries("2% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(3, Color.GREEN);
        timeseries = new TimeSeries("3% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(4, Color.MAGENTA);
        timeseries = new TimeSeries("3.5% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(5, Color.LIGHT_GRAY);
        timeseries = new TimeSeries("4% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(6, Color.YELLOW);
        timeseries = new TimeSeries("4.5% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(7, Color.PINK);
        timeseries = new TimeSeries("5% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(8, Color.RED);
        timeseries = new TimeSeries("5.5% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);

        xyItemRender.setSeriesPaint(9, Color.CYAN);
        timeseries = new TimeSeries("6% of community users removed", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);
    }
        break;
    case 2: {
        xyItemRender.setSeriesPaint(0, Color.GRAY);
        timeseries = new TimeSeries("Average number of thread replies (per hour)",
                org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);
    }
        break;
    case 3: {
        xyItemRender.setSeriesPaint(0, Color.GREEN);
        timeseries = new TimeSeries("New thread arrival activity change (%)", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);
        xyItemRender.setSeriesPaint(1, Color.BLUE);
        timeseries = new TimeSeries("Thread reply activity change (%)", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);
    }
        break;
    case 4: {
        xyItemRender.setSeriesPaint(0, Color.GREEN);
        timeseries = new TimeSeries("Mean thread aswer time", org.jfree.data.time.Hour.class);
        datasets[type].addSeries(timeseries);
    }
        break;
    }

    NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();
    //rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setTickUnit(new NumberTickUnit(0.1));

    xyplot.setBackgroundPaint(Color.lightGray);
    xyplot.setDomainGridlinePaint(Color.white);
    xyplot.setRangeGridlinePaint(Color.white);
    combineddomainxyplot.add(xyplot);

    ChartPanel chart = null;

    switch (type) {
    case 0: {
        jfreechart1 = new JFreeChart("", combineddomainxyplot);
        LegendTitle legendtitle = (LegendTitle) jfreechart1.getSubtitle(0);

        //set legend fonts
        jfreechart1.getLegend(0).setItemFont(new Font("Italic", Font.PLAIN, 11));

        legendtitle.setPosition(RectangleEdge.BOTTOM);
        legendtitle.setMargin(new RectangleInsets(UnitType.ABSOLUTE, 0.0D, 4D, 0.0D, 4D));
        jfreechart1.setBorderPaint(Color.black);
        jfreechart1.setBorderVisible(true);
        jfreechart1.setBackgroundPaint(Color.white);
        combineddomainxyplot.setBackgroundPaint(Color.lightGray);
        combineddomainxyplot.setDomainGridlinePaint(Color.white);
        combineddomainxyplot.setRangeGridlinePaint(Color.white);
        combineddomainxyplot.setAxisOffset(new RectangleInsets(4D, 4D, 4D, 4D));

        valueAxis1 = combineddomainxyplot.getDomainAxis();

        dateAxis1 = (DateAxis) valueAxis1;
        dateAxis1.setTickUnit(new DateTickUnit(1, 1));

        if (scope1 == 0) {
            valueAxis1.setAutoRange(true);
        } else {
            valueAxis1.setFixedAutoRange(scope1);
        }

        chart = new ChartPanel(jfreechart1);
        chart.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        //chart.add(buildPlotDisplayManagementPanel(valueAxis1, dateAxis1, ddlScope1));
        combineddomainxyplot.setInsets(new RectangleInsets(40, 25, 0, 10));
        chart.setPreferredSize(new Dimension(width, height));

        jfreechart1.setAntiAlias(false);
    }
        break;
    case 1: {

        jfreechart2 = new JFreeChart("", combineddomainxyplot);
        LegendTitle legendtitle = (LegendTitle) jfreechart2.getSubtitle(0);

        //set legend fonts
        jfreechart2.getLegend(0).setItemFont(new Font("Italic", Font.PLAIN, 11));

        legendtitle.setPosition(RectangleEdge.BOTTOM);
        legendtitle.setMargin(new RectangleInsets(UnitType.ABSOLUTE, 0.0D, 4D, 0.0D, 4D));
        jfreechart2.setBorderPaint(Color.black);
        jfreechart2.setBorderVisible(true);
        jfreechart2.setBackgroundPaint(Color.white);
        combineddomainxyplot.setBackgroundPaint(Color.lightGray);
        combineddomainxyplot.setDomainGridlinePaint(Color.white);
        combineddomainxyplot.setRangeGridlinePaint(Color.white);
        combineddomainxyplot.setAxisOffset(new RectangleInsets(4D, 4D, 4D, 4D));

        valueAxis2 = combineddomainxyplot.getDomainAxis();
        dateAxis2 = (DateAxis) valueAxis2;
        dateAxis2.setTickUnit(new DateTickUnit(1, 1));

        if (scope2 == 0) {
            valueAxis2.setAutoRange(true);
        } else {
            valueAxis2.setFixedAutoRange(scope2);
        }

        chart = new ChartPanel(jfreechart2);
        chart.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        combineddomainxyplot.setInsets(new RectangleInsets(40, 25, 0, 10));
        chart.setPreferredSize(new Dimension(width, height));

        jfreechart2.setAntiAlias(false);
    }
        break;
    case 2: {

        jfreechart3 = new JFreeChart("", combineddomainxyplot);
        LegendTitle legendtitle = (LegendTitle) jfreechart3.getSubtitle(0);

        //set legend fonts
        jfreechart3.getLegend(0).setItemFont(new Font("Italic", Font.PLAIN, 11));

        legendtitle.setPosition(RectangleEdge.BOTTOM);
        legendtitle.setMargin(new RectangleInsets(UnitType.ABSOLUTE, 0.0D, 4D, 0.0D, 4D));
        jfreechart3.setBorderPaint(Color.black);
        jfreechart3.setBorderVisible(true);
        jfreechart3.setBackgroundPaint(Color.white);
        combineddomainxyplot.setBackgroundPaint(Color.lightGray);
        combineddomainxyplot.setDomainGridlinePaint(Color.white);
        combineddomainxyplot.setRangeGridlinePaint(Color.white);
        combineddomainxyplot.setAxisOffset(new RectangleInsets(4D, 4D, 4D, 4D));

        valueAxis3 = combineddomainxyplot.getDomainAxis();
        dateAxis3 = (DateAxis) valueAxis3;

        if (scope3 == 0) {
            valueAxis3.setAutoRange(true);
        } else {
            valueAxis3.setFixedAutoRange(scope3);
        }

        chart = new ChartPanel(jfreechart3);
        chart.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        chart.add(buildPlotDisplayManagementPanel(valueAxis3, dateAxis3, ddlScope3));
        combineddomainxyplot.setInsets(new RectangleInsets(40, 25, 0, 10));
        chart.setPreferredSize(new Dimension(width, height));

        jfreechart3.setAntiAlias(false);
    }
        break;
    case 3: {
        jfreechart4 = new JFreeChart("", combineddomainxyplot);
        LegendTitle legendtitle = (LegendTitle) jfreechart4.getSubtitle(0);

        //set legend fonts
        jfreechart4.getLegend(0).setItemFont(new Font("Italic", Font.PLAIN, 11));

        legendtitle.setPosition(RectangleEdge.BOTTOM);
        legendtitle.setMargin(new RectangleInsets(UnitType.ABSOLUTE, 0.0D, 4D, 0.0D, 4D));
        jfreechart4.setBorderPaint(Color.black);
        jfreechart4.setBorderVisible(true);
        jfreechart4.setBackgroundPaint(Color.white);
        combineddomainxyplot.setBackgroundPaint(Color.lightGray);
        combineddomainxyplot.setDomainGridlinePaint(Color.white);
        combineddomainxyplot.setRangeGridlinePaint(Color.white);
        combineddomainxyplot.setAxisOffset(new RectangleInsets(4D, 4D, 4D, 4D));

        valueAxis4 = combineddomainxyplot.getDomainAxis();
        dateAxis4 = (DateAxis) valueAxis4;

        if (scope4 == 0) {
            valueAxis4.setAutoRange(true);
        } else {
            valueAxis4.setFixedAutoRange(scope4);
        }

        chart = new ChartPanel(jfreechart4);
        chart.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        chart.add(buildPlotDisplayManagementPanel(valueAxis4, dateAxis4, ddlScope4));
        combineddomainxyplot.setInsets(new RectangleInsets(40, 25, 0, 10));
        chart.setPreferredSize(new Dimension(width, height));

        jfreechart4.setAntiAlias(false);
    }
        break;
    case 4: {
        jfreechart5 = new JFreeChart("", combineddomainxyplot);
        LegendTitle legendtitle = (LegendTitle) jfreechart5.getSubtitle(0);

        //set legend fonts
        jfreechart5.getLegend(0).setItemFont(new Font("Italic", Font.PLAIN, 11));

        legendtitle.setPosition(RectangleEdge.BOTTOM);
        legendtitle.setMargin(new RectangleInsets(UnitType.ABSOLUTE, 0.0D, 4D, 0.0D, 4D));
        jfreechart5.setBorderPaint(Color.black);
        jfreechart5.setBorderVisible(true);
        jfreechart5.setBackgroundPaint(Color.white);
        combineddomainxyplot.setBackgroundPaint(Color.lightGray);
        combineddomainxyplot.setDomainGridlinePaint(Color.white);
        combineddomainxyplot.setRangeGridlinePaint(Color.white);
        combineddomainxyplot.setAxisOffset(new RectangleInsets(4D, 4D, 4D, 4D));

        valueAxis5 = combineddomainxyplot.getDomainAxis();
        dateAxis5 = (DateAxis) valueAxis5;

        if (scope5 == 0) {
            valueAxis5.setAutoRange(true);
        } else {
            valueAxis5.setFixedAutoRange(scope5);
        }

        chart = new ChartPanel(jfreechart5);
        chart.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        chart.add(buildPlotDisplayManagementPanel(valueAxis5, dateAxis5, ddlScope5));
        combineddomainxyplot.setInsets(new RectangleInsets(40, 25, 0, 10));
        chart.setPreferredSize(new Dimension(width, height));

        jfreechart5.setAntiAlias(false);
    }
        break;
    }

    return chart;

}

From source file:org.pentaho.plugin.jfreereport.reportcharts.AbstractChartExpression.java

protected void configureChart(final JFreeChart chart) {
    // Misc Properties
    final TextTitle chartTitle = chart.getTitle();
    if (chartTitle != null) {
        final Font titleFont = Font.decode(getTitleFont());
        chartTitle.setFont(titleFont);//from w  w w .j a va2s  .  com
    }

    if (isAntiAlias() == false) {
        chart.setAntiAlias(false);
    }

    chart.setBorderVisible(isShowBorder());

    final Color backgroundColor = parseColorFromString(getBackgroundColor());
    if (backgroundColor != null) {
        chart.setBackgroundPaint(backgroundColor);
    }

    if (plotBackgroundColor != null) {
        chart.getPlot().setBackgroundPaint(plotBackgroundColor);
    }
    chart.getPlot().setBackgroundAlpha(plotBackgroundAlpha);
    chart.getPlot().setForegroundAlpha(plotForegroundAlpha);
    final Color borderCol = parseColorFromString(getBorderColor());
    if (borderCol != null) {
        chart.setBorderPaint(borderCol);
    }

    //remove legend if showLegend = false
    if (!isShowLegend()) {
        chart.removeLegend();
    } else { //if true format legend
        final LegendTitle chLegend = chart.getLegend();
        if (chLegend != null) {
            final RectangleEdge loc = translateEdge(legendLocation.toLowerCase());
            if (loc != null) {
                chLegend.setPosition(loc);
            }
            if (getLegendFont() != null) {
                chLegend.setItemFont(Font.decode(getLegendFont()));
            }
            if (!isDrawLegendBorder()) {
                chLegend.setBorder(BlockBorder.NONE);
            }
            if (legendBackgroundColor != null) {
                chLegend.setBackgroundPaint(legendBackgroundColor);
            }
            if (legendTextColor != null) {
                chLegend.setItemPaint(legendTextColor);
            }
        }

    }

    final Plot plot = chart.getPlot();
    plot.setNoDataMessageFont(Font.decode(getLabelFont()));

    final String message = getNoDataMessage();
    if (message != null) {
        plot.setNoDataMessage(message);
    }

    plot.setOutlineVisible(isChartSectionOutline());

    if (backgroundImage != null) {
        if (plotImageCache != null) {
            plot.setBackgroundImage(plotImageCache);
        } else {
            final ExpressionRuntime expressionRuntime = getRuntime();
            final ProcessingContext context = expressionRuntime.getProcessingContext();
            final ResourceKey contentBase = context.getContentBase();
            final ResourceManager manager = context.getResourceManager();
            try {
                final ResourceKey key = createKeyFromString(manager, contentBase, backgroundImage);
                final Resource resource = manager.create(key, null, Image.class);
                final Image image = (Image) resource.getResource();
                plot.setBackgroundImage(image);
                plotImageCache = image;
            } catch (Exception e) {
                logger.error("ABSTRACTCHARTEXPRESSION.ERROR_0007_ERROR_RETRIEVING_PLOT_IMAGE", e); //$NON-NLS-1$
                throw new IllegalStateException("Failed to process chart");
            }
        }
    }
}

From source file:com.chart.SwingChart.java

/**
 * Send node to printer/*from w  ww  .  j  av a2  s  .  c om*/
 * @param node JavaFX node
 */
public final void print(final Node node) {
    LegendTitle legend = new LegendTitle(chart.getPlot());
    legend.setItemFont(legend.getItemFont().deriveFont(fontSize));
    chart.addLegend(legend);
    legend.setPosition(RectangleEdge.BOTTOM);
    chart.setTitle(name);
    chartPanel.createChartPrintJob();
    chart.removeLegend();
    chart.setTitle("");
}

From source file:net.sf.jasperreports.components.spiderchart.FillSpiderChart.java

protected JFreeChart evaluateChart(byte evaluation) throws JRException {
    maxValue = (Double) fillContext.evaluate(getPlot().getMaxValueExpression(), evaluation);
    titleText = (String) fillContext.evaluate(getChartSettings().getTitleExpression(), evaluation);
    subtitleText = (String) fillContext.evaluate(getChartSettings().getSubtitleExpression(), evaluation);
    anchorName = (String) fillContext.evaluate(getChartSettings().getAnchorNameExpression(), evaluation);
    hyperlinkReference = (String) fillContext.evaluate(getChartSettings().getHyperlinkReferenceExpression(),
            evaluation);//from w w w  . ja  v a  2  s .  co m
    hyperlinkAnchor = (String) fillContext.evaluate(getChartSettings().getHyperlinkAnchorExpression(),
            evaluation);
    hyperlinkPage = (Integer) fillContext.evaluate(getChartSettings().getHyperlinkPageExpression(), evaluation);
    hyperlinkTooltip = (String) fillContext.evaluate(getChartSettings().getHyperlinkTooltipExpression(),
            evaluation);
    hyperlinkParameters = JRFillHyperlinkHelper.evaluateHyperlinkParameters(getChartSettings(),
            expressionEvaluator, evaluation);

    dataset.evaluateDatasetRun(evaluation);
    dataset.finishDataset();

    chartHyperlinkProvider = new CategoryChartHyperlinkProvider(dataset.getItemHyperlinks());

    bookmarkLevel = getChartSettings().getBookmarkLevel();

    SpiderWebPlot spiderWebPlot = new SpiderWebPlot((DefaultCategoryDataset) dataset.getCustomDataset());

    if (getPlot().getAxisLineColor() != null) {
        spiderWebPlot.setAxisLinePaint(getPlot().getAxisLineColor());
    }
    if (getPlot().getAxisLineWidth() != null) {
        spiderWebPlot.setAxisLineStroke(new BasicStroke(getPlot().getAxisLineWidth()));
    }
    if (getPlot().getBackcolor() != null) {
        spiderWebPlot.setBackgroundPaint(getPlot().getBackcolor());
    }
    if (getPlot().getBackgroundAlpha() != null) {
        spiderWebPlot.setBackgroundAlpha(getPlot().getBackgroundAlpha());
    }
    if (getPlot().getForegroundAlpha() != null) {
        spiderWebPlot.setForegroundAlpha(getPlot().getForegroundAlpha());
    }
    if (getPlot().getHeadPercent() != null) {
        spiderWebPlot.setHeadPercent(getPlot().getHeadPercent());
    }
    if (getPlot().getInteriorGap() != null) {
        spiderWebPlot.setInteriorGap(getPlot().getInteriorGap());
    }
    if (getPlot().getLabelColor() != null) {
        spiderWebPlot.setLabelPaint(getPlot().getLabelColor());
    }
    if (getPlot().getLabelFont() != null) {
        spiderWebPlot.setLabelFont(JRFontUtil.getAwtFont(getPlot().getLabelFont(), Locale.getDefault()));
    }
    if (getPlot().getLabelGap() != null) {
        spiderWebPlot.setAxisLabelGap(getPlot().getLabelGap());
    }
    if (maxValue != null) {
        spiderWebPlot.setMaxValue(maxValue);
    }
    if (getPlot().getRotation() != null) {
        spiderWebPlot.setDirection(getPlot().getRotation().getRotation());
    }
    if (getPlot().getStartAngle() != null) {
        spiderWebPlot.setStartAngle(getPlot().getStartAngle());
    }
    if (getPlot().getTableOrder() != null) {
        spiderWebPlot.setDataExtractOrder(getPlot().getTableOrder().getOrder());
    }
    if (getPlot().getWebFilled() != null) {
        spiderWebPlot.setWebFilled(getPlot().getWebFilled());
    }

    spiderWebPlot.setToolTipGenerator(new StandardCategoryToolTipGenerator());
    spiderWebPlot.setLabelGenerator(new StandardCategoryItemLabelGenerator());

    Font titleFont = getChartSettings().getTitleFont() != null
            ? JRFontUtil.getAwtFont(getChartSettings().getTitleFont(), Locale.getDefault())
            : TextTitle.DEFAULT_FONT;

    JFreeChart jfreechart = new JFreeChart(titleText, titleFont, spiderWebPlot, true);

    if (chartSettings.getBackcolor() != null) {
        jfreechart.setBackgroundPaint(chartSettings.getBackcolor());
    }

    RectangleEdge titleEdge = getEdge(getChartSettings().getTitlePosition(), RectangleEdge.TOP);

    if (titleText != null) {
        TextTitle title = jfreechart.getTitle();
        title.setText(titleText);
        if (getChartSettings().getTitleColor() != null) {
            title.setPaint(getChartSettings().getTitleColor());
        }

        title.setFont(titleFont);
        title.setPosition(titleEdge);
        jfreechart.setTitle(title);
    }

    if (subtitleText != null) {
        TextTitle subtitle = new TextTitle(subtitleText);
        subtitle.setText(subtitleText);
        if (getChartSettings().getSubtitleColor() != null) {
            subtitle.setPaint(getChartSettings().getSubtitleColor());
        }

        if (getChartSettings().getSubtitleColor() != null) {
            Font subtitleFont = getChartSettings().getSubtitleFont() != null
                    ? JRFontUtil.getAwtFont(getChartSettings().getSubtitleFont(), Locale.getDefault())
                    : TextTitle.DEFAULT_FONT;
            subtitle.setFont(subtitleFont);
        }

        subtitle.setPosition(titleEdge);

        jfreechart.addSubtitle(subtitle);
    }

    // Apply all of the legend formatting options
    LegendTitle legend = jfreechart.getLegend();

    if (legend != null) {
        legend.setVisible((chartSettings.getShowLegend() == null || chartSettings.getShowLegend()));
        if (legend.isVisible()) {
            if (getChartSettings().getLegendColor() != null) {
                legend.setItemPaint(getChartSettings().getLegendColor());
            }
            if (getChartSettings().getLegendBackgroundColor() != null) {
                legend.setBackgroundPaint(getChartSettings().getLegendBackgroundColor());
            }

            if (getChartSettings().getLegendFont() != null) {
                legend.setItemFont(
                        JRFontUtil.getAwtFont(getChartSettings().getLegendFont(), Locale.getDefault()));
            }
            legend.setPosition(getEdge(getChartSettings().getLegendPosition(), RectangleEdge.BOTTOM));
        }
    }
    return jfreechart;

}

From source file:com.smhdemo.common.report.generate.factory.ChartFactory.java

public byte[] export(Chart report, Map<String, String> pageParams) throws Exception {
    if (report == null) {
        return null;
    }//from  www  .ja  v a  2 s  .c  o  m
    DefaultCategoryDataset dataset = buildDataset(report, pageParams);
    java.awt.Font titleFont = new java.awt.Font(report.getFontName(), report.getFontStyle(),
            report.getFontSize());
    String chartTitle = report.getChartTitle();
    chartTitle = replaceParam(pageParams, report.getParameters(), chartTitle, false);
    String horizAxisLabel = report.getHorizAxisLabel();
    horizAxisLabel = replaceParam(pageParams, report.getParameters(), horizAxisLabel, false);
    String vertAxisLabel = report.getVertAxisLabel();
    vertAxisLabel = replaceParam(pageParams, report.getParameters(), vertAxisLabel, false);
    Boolean showLegend = report.getShowLegend();
    Boolean showTooltips = report.getShowTooltips();
    Boolean drillThroughEnabled = false;
    Chart.Type chartType = report.getType();

    CategoryURLGenerator urlGenerator = null;

    JFreeChart chart = null;
    switch (chartType) {
    case VERTBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case VERTBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDHORIZBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case STACKEDHORIZBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case VERTLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case PIEBYCOLUMN:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYROW:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYCOLUMN3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);

        break;
    case PIEBYROW3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    default:
        throw new BaseException("", "");
    }
    try {
        Integer bgColorR = report.getBgColorR();
        Integer bgColorG = report.getBgColorG();
        Integer bgColorB = report.getBgColorB();
        chart.setBackgroundPaint(new java.awt.Color(bgColorR, bgColorG, bgColorB));

        String axisFontName = report.getAxisFontName();
        Integer axisFontStyle = report.getAxisFontStyle();
        Integer axisFontSize = report.getAxisFontSize();
        java.awt.Font axisFont = new java.awt.Font(axisFontName, axisFontStyle, axisFontSize);

        String axisTickFontName = report.getAxisTickFontName();
        Integer axisTickFontStyle = report.getAxisTickFontStyle();
        Integer axisTickFontSize = report.getAxisTickFontSize();
        java.awt.Font axisTickFont = new java.awt.Font(axisTickFontName, axisTickFontStyle, axisTickFontSize);

        String legendFontName = report.getLegendFontName();
        Integer legendFontStyle = report.getLegendFontStyle();
        Integer legendFontSize = report.getLegendFontSize();
        java.awt.Font legendFont = new java.awt.Font(legendFontName, legendFontStyle, legendFontSize);
        Integer tickLabelRotate = report.getTickLabelRotate();

        String dataFontName = report.getDataFontName();
        Integer dataFontStyle = report.getDataFontStyle();
        Integer dataFontSize = report.getDataFontSize();
        java.awt.Font dataFont = new java.awt.Font(dataFontName, dataFontStyle, dataFontSize);

        Plot plot = chart.getPlot();
        if (!(plot instanceof MultiplePiePlot)) {
            CategoryPlot categoryPlot = chart.getCategoryPlot();
            CategoryItemRenderer renderer = categoryPlot.getRenderer();
            renderer.setBaseItemLabelGenerator(new LabelGenerator(0.0));
            renderer.setBaseItemLabelFont(dataFont);
            renderer.setBaseItemLabelsVisible(true);
            if (chartType == Chart.Type.VERTLINE || chartType == Chart.Type.HORIZLINE) {
                LineAndShapeRenderer lineRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
                lineRenderer.setBaseShapesVisible(true);
                lineRenderer.setDrawOutlines(true);
                lineRenderer.setUseFillPaint(true);
            }
        }

        if (plot instanceof CategoryPlot) {
            CategoryPlot catPlot = (CategoryPlot) plot;
            catPlot.getDomainAxis().setLabelFont(axisFont);
            catPlot.getRangeAxis().setLabelFont(axisFont);
            catPlot.getDomainAxis().setTickLabelFont(axisTickFont);
            catPlot.getRangeAxis().setTickLabelFont(axisTickFont);
            catPlot.getDomainAxis().setMaximumCategoryLabelWidthRatio(100.0f);
            double angle = -2.0 * Math.PI / 360.0 * (double) tickLabelRotate;
            CategoryLabelPositions oldp = catPlot.getDomainAxis().getCategoryLabelPositions();
            CategoryLabelPositions newp = new CategoryLabelPositions(oldp.getLabelPosition(RectangleEdge.TOP),
                    new CategoryLabelPosition(RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT,
                            TextAnchor.TOP_RIGHT, angle, CategoryLabelWidthType.RANGE, 0.0f),
                    oldp.getLabelPosition(RectangleEdge.LEFT), oldp.getLabelPosition(RectangleEdge.RIGHT));
            catPlot.getDomainAxis().setCategoryLabelPositions(newp);
        } else if (plot instanceof PiePlot3D) {
            PiePlot3D piePlot = (PiePlot3D) plot;
            piePlot.setLabelFont(axisFont);
            piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE);
            piePlot.setForegroundAlpha(0.5f);
            piePlot.setNoDataMessage("?");
        } else if (plot instanceof PiePlot) {
            PiePlot piePlot = (PiePlot) plot;
            piePlot.setLabelFont(axisFont);
        }
        LegendTitle legend = (LegendTitle) chart.getLegend();
        if (legend != null) {
            legend.setItemFont(legendFont);
            RectangleEdge legendRectEdge = RectangleEdge.BOTTOM;
            Integer legendPosition = report.getLegendPosition();
            switch (legendPosition) {
            case 0:
                legendRectEdge = RectangleEdge.LEFT;
                break;
            case 1:
                legendRectEdge = RectangleEdge.TOP;
                break;
            case 2:
                legendRectEdge = RectangleEdge.RIGHT;
                break;
            case 3:
                legendRectEdge = RectangleEdge.BOTTOM;
                break;
            }
            legend.setPosition(legendRectEdge);
        }
    } catch (Exception e) {
        logger.error("Chart Export Exception", e);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(out, chart, report.getChartWidth(), report.getChartHeight());
    return out.toByteArray();
}

From source file:com.ewcms.plugin.report.generate.factory.ChartFactory.java

public byte[] export(ChartReport report, Map<String, String> pageParams) throws Exception {
    if (report == null) {
        return null;
    }//  ww  w  .ja v  a2  s. com
    DefaultCategoryDataset dataset = buildDataset(report, pageParams);
    java.awt.Font titleFont = new java.awt.Font(report.getFontName(), report.getFontStyle(),
            report.getFontSize());
    String chartTitle = report.getChartTitle();
    chartTitle = replaceParam(pageParams, report.getParameters(), chartTitle, false);
    String horizAxisLabel = report.getHorizAxisLabel();
    horizAxisLabel = replaceParam(pageParams, report.getParameters(), horizAxisLabel, false);
    String vertAxisLabel = report.getVertAxisLabel();
    vertAxisLabel = replaceParam(pageParams, report.getParameters(), vertAxisLabel, false);
    Boolean showLegend = report.getShowLegend();
    Boolean showTooltips = report.getShowTooltips();
    Boolean drillThroughEnabled = false;
    ChartReport.Type chartType = report.getType();

    CategoryURLGenerator urlGenerator = null;

    JFreeChart chart = null;
    switch (chartType) {
    case VERTBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case VERTBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDHORIZBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case STACKEDHORIZBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case VERTLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case PIEBYCOLUMN:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYROW:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYCOLUMN3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);

        break;
    case PIEBYROW3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    default:
        throw new BaseException("", "");
    }
    try {
        Integer bgColorR = report.getBgColorR();
        Integer bgColorG = report.getBgColorG();
        Integer bgColorB = report.getBgColorB();
        chart.setBackgroundPaint(new java.awt.Color(bgColorR, bgColorG, bgColorB));

        String axisFontName = report.getAxisFontName();
        Integer axisFontStyle = report.getAxisFontStyle();
        Integer axisFontSize = report.getAxisFontSize();
        java.awt.Font axisFont = new java.awt.Font(axisFontName, axisFontStyle, axisFontSize);

        String axisTickFontName = report.getAxisTickFontName();
        Integer axisTickFontStyle = report.getAxisTickFontStyle();
        Integer axisTickFontSize = report.getAxisTickFontSize();
        java.awt.Font axisTickFont = new java.awt.Font(axisTickFontName, axisTickFontStyle, axisTickFontSize);

        String legendFontName = report.getLegendFontName();
        Integer legendFontStyle = report.getLegendFontStyle();
        Integer legendFontSize = report.getLegendFontSize();
        java.awt.Font legendFont = new java.awt.Font(legendFontName, legendFontStyle, legendFontSize);
        Integer tickLabelRotate = report.getTickLabelRotate();

        String dataFontName = report.getDataFontName();
        Integer dataFontStyle = report.getDataFontStyle();
        Integer dataFontSize = report.getDataFontSize();
        java.awt.Font dataFont = new java.awt.Font(dataFontName, dataFontStyle, dataFontSize);

        Plot plot = chart.getPlot();
        if (!(plot instanceof MultiplePiePlot)) {
            CategoryPlot categoryPlot = chart.getCategoryPlot();
            CategoryItemRenderer renderer = categoryPlot.getRenderer();
            renderer.setBaseItemLabelGenerator(new LabelGenerator(0.0));
            renderer.setBaseItemLabelFont(dataFont);
            renderer.setBaseItemLabelsVisible(true);
            if (chartType == ChartReport.Type.VERTLINE || chartType == ChartReport.Type.HORIZLINE) {
                LineAndShapeRenderer lineRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
                lineRenderer.setBaseShapesVisible(true);
                lineRenderer.setDrawOutlines(true);
                lineRenderer.setUseFillPaint(true);
            }
        }

        if (plot instanceof CategoryPlot) {
            CategoryPlot catPlot = (CategoryPlot) plot;
            catPlot.getDomainAxis().setLabelFont(axisFont);
            catPlot.getRangeAxis().setLabelFont(axisFont);
            catPlot.getDomainAxis().setTickLabelFont(axisTickFont);
            catPlot.getRangeAxis().setTickLabelFont(axisTickFont);
            catPlot.getDomainAxis().setMaximumCategoryLabelWidthRatio(100.0f);
            double angle = -2.0 * Math.PI / 360.0 * (double) tickLabelRotate;
            CategoryLabelPositions oldp = catPlot.getDomainAxis().getCategoryLabelPositions();
            CategoryLabelPositions newp = new CategoryLabelPositions(oldp.getLabelPosition(RectangleEdge.TOP),
                    new CategoryLabelPosition(RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT,
                            TextAnchor.TOP_RIGHT, angle, CategoryLabelWidthType.RANGE, 0.0f),
                    oldp.getLabelPosition(RectangleEdge.LEFT), oldp.getLabelPosition(RectangleEdge.RIGHT));
            catPlot.getDomainAxis().setCategoryLabelPositions(newp);
        } else if (plot instanceof PiePlot3D) {
            PiePlot3D piePlot = (PiePlot3D) plot;
            piePlot.setLabelFont(axisFont);
            piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE);
            piePlot.setForegroundAlpha(0.5f);
            piePlot.setNoDataMessage("?");
        } else if (plot instanceof PiePlot) {
            PiePlot piePlot = (PiePlot) plot;
            piePlot.setLabelFont(axisFont);
        }
        LegendTitle legend = (LegendTitle) chart.getLegend();
        if (legend != null) {
            legend.setItemFont(legendFont);
            RectangleEdge legendRectEdge = RectangleEdge.BOTTOM;
            Integer legendPosition = report.getLegendPosition();
            switch (legendPosition) {
            case 0:
                legendRectEdge = RectangleEdge.LEFT;
                break;
            case 1:
                legendRectEdge = RectangleEdge.TOP;
                break;
            case 2:
                legendRectEdge = RectangleEdge.RIGHT;
                break;
            case 3:
                legendRectEdge = RectangleEdge.BOTTOM;
                break;
            }
            legend.setPosition(legendRectEdge);
        }
    } catch (Exception e) {
        logger.error("Chart Export Exception", e);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(out, chart, report.getChartWidth(), report.getChartHeight());
    return out.toByteArray();
}