Example usage for org.jfree.chart JFreeChart getTitle

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

Introduction

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

Prototype

public TextTitle getTitle() 

Source Link

Document

Returns the main chart title.

Usage

From source file:UserInfo_Frame.java

private void barChart_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_barChart_btnActionPerformed
    //create dataset values
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.setValue(80, "Marks", "Student1");
    dataset.setValue(50, "Marks", "Student2");
    dataset.setValue(75, "Marks", "Student3");
    dataset.setValue(95, "Marks", "Student4");
    //create bar chart
    JFreeChart chart = ChartFactory.createBarChart("Student Score", "Student Name", "Marks", dataset,
            PlotOrientation.VERTICAL, false, true, true);
    // create Line chart FreeChart chart = ChartFactory.createLineChart("Student Score", "Student Name", "Marks", dataset,PlotOrientation.VERTICAL,false,true,true);
    // set properties
    chart.setBackgroundPaint(Color.YELLOW);// change background color to yellow
    chart.getTitle().setPaint(Color.RED);

    CategoryPlot p = chart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.BLUE);
    ChartFrame bframe = new ChartFrame("Bar Chart for student", chart);
    bframe.setVisible(true);/*ww  w .j ava  2s  .com*/
    bframe.setSize(450, 350);

}

From source file:ds.monte.carlo.Application.java

private void createLengthGraph(HashMap<Integer, Integer> probability) {
    DefaultCategoryDataset pDataset = new DefaultCategoryDataset();

    for (Integer key : probability.keySet()) {
        pDataset.setValue(probability.get(key), "", "" + key);
    }//from  ww  w  .j  av  a 2  s  .  c o m

    JFreeChart growChart = ChartFactory.createLineChart("Simulated annealing", "", "", pDataset,
            PlotOrientation.VERTICAL, false, false, false);
    growChart.setBackgroundPaint(Color.WHITE);

    CategoryPlot catPlot = growChart.getCategoryPlot();
    catPlot.setRangeGridlinePaint(new Color(92, 184, 92));

    ValueAxis vAxis = catPlot.getRangeAxis();
    CategoryAxis cAxis = catPlot.getDomainAxis();

    cAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    cAxis.setTickLabelsVisible(false);

    Font font = new Font("SansSerif", Font.PLAIN, 12);
    Font fontTitle = new Font("SansSerif", Font.PLAIN, 14);
    vAxis.setTickLabelFont(font);
    growChart.getTitle().setFont(fontTitle);

    LineAndShapeRenderer renderer = (LineAndShapeRenderer) catPlot.getRenderer();
    Color bootstrapGreen = new Color(92, 184, 92);
    renderer.setSeriesPaint(0, bootstrapGreen);

    ChartPanel chartPanel = new ChartPanel(growChart);
    jPanel9.removeAll();
    jPanel9.add(chartPanel, BorderLayout.CENTER);
    jPanel9.validate();
}

From source file:ds.monte.carlo.Application.java

private void createFrequencyGraph(HashMap<Long, Integer> dictionary) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    long checksum = 0;

    for (Long key : dictionary.keySet()) {
        dataset.setValue(dictionary.get(key), "", "" + key);
        checksum += dictionary.get(key);
    }/*from w  w  w  .  j a va  2  s.  c  om*/

    JFreeChart chart = ChartFactory.createBarChart("Frequency graph", "", "", dataset, PlotOrientation.VERTICAL,
            false, false, false);
    chart.setBackgroundPaint(Color.WHITE);
    CategoryPlot catPlot = chart.getCategoryPlot();
    catPlot.setRangeGridlinePaint(new Color(92, 184, 92));

    ValueAxis vAxis = catPlot.getRangeAxis();
    CategoryAxis cAxis = catPlot.getDomainAxis();

    cAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);

    Font font = new Font("SansSerif", Font.PLAIN, 12);
    Font fontTitle = new Font("SansSerif", Font.PLAIN, 14);
    Font fontc = new Font("SansSerif", Font.PLAIN, 10);
    vAxis.setTickLabelFont(font);
    chart.getTitle().setFont(fontTitle);
    cAxis.setTickLabelFont(fontc);

    BarRenderer renderer = (BarRenderer) catPlot.getRenderer();
    Color bootstrapGreen = new Color(92, 184, 92);
    renderer.setSeriesPaint(0, bootstrapGreen);

    ChartPanel chartPanel = new ChartPanel(chart);
    jPanel5.removeAll();
    jPanel5.add(chartPanel, BorderLayout.CENTER);
    jPanel5.validate();
    //jPanel5.setVisible(true);

    System.out.println("Checksum " + checksum);
    System.out.println("NumberOfReplications " + numberOfReplications);

}

From source file:net.sf.fspdfs.chartthemes.spring.EyeCandySixtiesChartTheme.java

/**
 *
 *//*from  ww  w .  jav  a 2  s  .  c o  m*/
protected void configureChart(JFreeChart jfreeChart, JRChartPlot jrPlot) throws JRException {
    super.configureChart(jfreeChart, jrPlot);

    TextTitle title = jfreeChart.getTitle();
    if (title != null) {
        RectangleInsets padding = title.getPadding();
        double bottomPadding = Math.max(padding.getBottom(), 15d);
        title.setPadding(padding.getTop(), padding.getLeft(), bottomPadding, padding.getRight());
    }

    GradientPaint gp = (GradientPaint) getDefaultValue(defaultChartPropertiesMap,
            ChartThemesConstants.BACKGROUND_PAINT);

    jfreeChart.setBackgroundPaint(new GradientPaint(0f, 0f, gp.getColor1(), 0f, getChart().getHeight() * 0.7f,
            gp.getColor2(), false));
}

From source file:org.openmrs.web.servlet.ShowGraphServlet.java

/**
 * The main method for this class. It will create a JFreeChart object to be written to the
 * response./* w w w.j a  v a2 s .  c o  m*/
 *
 * @param request the current request will all the parameters needed
 * @return JFreeChart object to be rendered
 * @should set value axis label to given units
 * @should set value axis label to concept numeric units if given units is null
 */
protected JFreeChart getChart(HttpServletRequest request) {
    // All available GET parameters
    String patientId = request.getParameter("patientId"); // required
    String conceptId1 = request.getParameter("conceptId"); // required
    String conceptId2 = request.getParameter("conceptId2");
    String chartTitle = request.getParameter("chartTitle");
    String units = request.getParameter("units");

    String minRangeString = request.getParameter("minRange");
    String maxRangeString = request.getParameter("maxRange");

    String hideDate = request.getParameter("hideDate");

    Patient patient = Context.getPatientService().getPatient(Integer.parseInt(patientId));

    // Set date range to passed values, otherwise set a default date range to the last 12 months
    Calendar cal = Calendar.getInstance();
    Date fromDate = getFromDate(request.getParameter("fromDate"));
    Date toDate = getToDate(request.getParameter("toDate"));

    // Swap if fromDate is after toDate
    if (fromDate.getTime() > toDate.getTime()) {
        Long temp = fromDate.getTime();
        fromDate.setTime(toDate.getTime());
        toDate.setTime(temp);
    }

    // Graph parameters
    Double minRange = null;
    Double maxRange = null;
    Double normalLow = null;
    Double normalHigh = null;
    Double criticalLow = null;
    Double criticalHigh = null;
    String timeAxisTitle = null;
    String rangeAxisTitle = null;
    boolean userSpecifiedMaxRange = false;
    boolean userSpecifiedMinRange = false;

    // Fetching obs
    List<Obs> observations1 = new ArrayList<Obs>();
    List<Obs> observations2 = new ArrayList<Obs>();
    Concept concept1 = null, concept2 = null;
    if (conceptId1 != null) {
        concept1 = Context.getConceptService().getConcept(Integer.parseInt(conceptId1));
    }
    if (conceptId2 != null) {
        concept2 = Context.getConceptService().getConcept(Integer.parseInt(conceptId2));
    }
    if (concept1 != null) {
        observations1 = Context.getObsService().getObservationsByPersonAndConcept(patient, concept1);
        chartTitle = concept1.getName().getName();
        rangeAxisTitle = ((ConceptNumeric) concept1).getUnits();
        minRange = ((ConceptNumeric) concept1).getLowAbsolute();
        maxRange = ((ConceptNumeric) concept1).getHiAbsolute();
        normalLow = ((ConceptNumeric) concept1).getLowNormal();
        normalHigh = ((ConceptNumeric) concept1).getHiNormal();
        criticalLow = ((ConceptNumeric) concept1).getLowCritical();
        criticalHigh = ((ConceptNumeric) concept1).getHiCritical();

        // Only get observations2 if both concepts share the same units; update chart title and ranges
        if (concept2 != null) {
            String concept2Units = ((ConceptNumeric) concept2).getUnits();
            if (concept2Units != null && concept2Units.equals(rangeAxisTitle)) {
                observations2 = Context.getObsService().getObservationsByPersonAndConcept(patient, concept2);
                chartTitle += " + " + concept2.getName().getName();
                if (((ConceptNumeric) concept2).getHiAbsolute() != null
                        && ((ConceptNumeric) concept2).getHiAbsolute() > maxRange) {
                    maxRange = ((ConceptNumeric) concept2).getHiAbsolute();
                }
                if (((ConceptNumeric) concept2).getLowAbsolute() != null
                        && ((ConceptNumeric) concept2).getLowAbsolute() < minRange) {
                    minRange = ((ConceptNumeric) concept2).getLowAbsolute();
                }
            } else {
                log.warn("Units for concept id: " + conceptId2 + " don't match units for concept id: "
                        + conceptId1 + ". Only displaying " + conceptId1);
                concept2 = null; // nullify concept2 so that the legend isn't shown later
            }
        }
    } else {
        chartTitle = "Concept " + conceptId1 + " not found";
        rangeAxisTitle = "Value";
    }

    // Overwrite with user-specified values, otherwise use default values
    if (units != null && units.length() > 0) {
        rangeAxisTitle = units;
    }
    if (minRangeString != null) {
        minRange = Double.parseDouble(minRangeString);
        userSpecifiedMinRange = true;
    }
    if (maxRangeString != null) {
        maxRange = Double.parseDouble(maxRangeString);
        userSpecifiedMaxRange = true;
    }
    if (chartTitle == null) {
        chartTitle = "";
    }
    if (rangeAxisTitle == null) {
        rangeAxisTitle = "";
    }
    if (minRange == null) {
        minRange = 0.0;
    }
    if (maxRange == null) {
        maxRange = 200.0;
    }

    // Create data set
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeries series1, series2;

    // Interval-dependent units
    Class<? extends RegularTimePeriod> timeScale = null;
    if (toDate.getTime() - fromDate.getTime() <= 86400000) {
        // Interval <= 1 day: minutely
        timeScale = Minute.class;
        timeAxisTitle = "Time";
    } else if (toDate.getTime() - fromDate.getTime() <= 259200000) {
        // Interval <= 3 days: hourly
        timeScale = Hour.class;
        timeAxisTitle = "Time";
    } else {
        timeScale = Day.class;
        timeAxisTitle = "Date";
    }
    if (concept1 == null) {
        series1 = new TimeSeries("NULL", Hour.class);
    } else {
        series1 = new TimeSeries(concept1.getName().getName(), timeScale);
    }
    if (concept2 == null) {
        series2 = new TimeSeries("NULL", Hour.class);
    } else {
        series2 = new TimeSeries(concept2.getName().getName(), timeScale);
    }

    // Add data points for concept1
    for (Obs obs : observations1) {
        if (obs.getValueNumeric() != null && obs.getObsDatetime().getTime() >= fromDate.getTime()
                && obs.getObsDatetime().getTime() < toDate.getTime()) {
            cal.setTime(obs.getObsDatetime());
            if (timeScale == Minute.class) {
                Minute min = new Minute(cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY),
                        cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series1.addOrUpdate(min, obs.getValueNumeric());
            } else if (timeScale == Hour.class) {
                Hour hour = new Hour(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH),
                        cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series1.addOrUpdate(hour, obs.getValueNumeric());
            } else {
                Day day = new Day(cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1,
                        cal.get(Calendar.YEAR));
                series1.addOrUpdate(day, obs.getValueNumeric());
            }
        }
    }

    // Add data points for concept2
    for (Obs obs : observations2) {
        if (obs.getValueNumeric() != null && obs.getObsDatetime().getTime() >= fromDate.getTime()
                && obs.getObsDatetime().getTime() < toDate.getTime()) {
            cal.setTime(obs.getObsDatetime());
            if (timeScale == Minute.class) {
                Minute min = new Minute(cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY),
                        cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series2.addOrUpdate(min, obs.getValueNumeric());
            } else if (timeScale == Hour.class) {
                Hour hour = new Hour(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH),
                        cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series2.addOrUpdate(hour, obs.getValueNumeric());
            } else {
                Day day = new Day(cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1,
                        cal.get(Calendar.YEAR));
                series2.addOrUpdate(day, obs.getValueNumeric());
            }
        }
    }

    // Add series to dataset
    dataset.addSeries(series1);
    if (!series2.isEmpty()) {
        dataset.addSeries(series2);
    }

    // As of JFreeChart 1.0.11 the default background color is dark grey instead of white.
    // This line restores the original white background.
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());

    JFreeChart chart = null;

    // Show legend only if more than one series
    if (concept2 == null) {
        chart = ChartFactory.createTimeSeriesChart(chartTitle, timeAxisTitle, rangeAxisTitle, dataset, false,
                false, false);
    } else {
        chart = ChartFactory.createTimeSeriesChart(chartTitle, timeAxisTitle, rangeAxisTitle, dataset, true,
                false, false);
    }

    // Customize title font
    Font font = new Font("Arial", Font.BOLD, 12);
    TextTitle title = chart.getTitle();
    title.setFont(font);
    chart.setTitle(title);

    // Add subtitle, unless 'hideDate' has been passed
    if (hideDate == null) {
        TextTitle subtitle = new TextTitle(fromDate.toString() + " - " + toDate.toString());
        subtitle.setFont(font);
        chart.addSubtitle(subtitle);
    }

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setNoDataMessage("No Data Available");

    // Add abnormal/critical range background color (only for single-concept graphs)
    if (concept2 == null) {
        IntervalMarker abnormalLow, abnormalHigh, critical;
        if (normalHigh != null) {
            abnormalHigh = new IntervalMarker(normalHigh, maxRange, COLOR_ABNORMAL);
            plot.addRangeMarker(abnormalHigh);
        }
        if (normalLow != null) {
            abnormalLow = new IntervalMarker(minRange, normalLow, COLOR_ABNORMAL);
            plot.addRangeMarker(abnormalLow);
        }
        if (criticalHigh != null) {
            critical = new IntervalMarker(criticalHigh, maxRange, COLOR_CRITICAL);
            plot.addRangeMarker(critical);
        }
        if (criticalLow != null) {
            critical = new IntervalMarker(minRange, criticalLow, COLOR_CRITICAL);
            plot.addRangeMarker(critical);
        }

        // there is data outside of the absolute lower limits for this concept (or of what the user specified as minrange)
        if (plot.getRangeAxis().getLowerBound() < minRange) {
            IntervalMarker error = new IntervalMarker(plot.getRangeAxis().getLowerBound(), minRange,
                    COLOR_ERROR);
            plot.addRangeMarker(error);
        }

        if (plot.getRangeAxis().getUpperBound() > maxRange) {
            IntervalMarker error = new IntervalMarker(maxRange, plot.getRangeAxis().getUpperBound(),
                    COLOR_ERROR);
            plot.addRangeMarker(error);
        }

    }

    // Visuals
    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setBaseShapesFilled(true);
        renderer.setBaseShapesVisible(true);
    }

    // Customize the plot (range and domain axes)

    // Modify x-axis (datetime)
    DateAxis timeAxis = (DateAxis) plot.getDomainAxis();
    if (timeScale == Day.class) {
        timeAxis.setDateFormatOverride(new SimpleDateFormat("dd-MMM-yyyy"));
    }

    timeAxis.setRange(fromDate, toDate);

    // Set y-axis range (values)
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    if (userSpecifiedMinRange) {
        minRange = (rangeAxis.getLowerBound() < minRange) ? rangeAxis.getLowerBound() : minRange;
    }

    if (userSpecifiedMaxRange) {
        // otherwise we just use default range
        maxRange = (rangeAxis.getUpperBound() > maxRange) ? rangeAxis.getUpperBound() : maxRange;
    }

    rangeAxis.setRange(minRange, maxRange);

    return chart;
}

From source file:edu.jhuapl.graphs.controller.GraphController.java

private void writeGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap,
        boolean includeFooter, boolean includeButtons, String callBackURL, String graphOptionsHelpLink,
        String downloadHelpLink, GraphObject graph) {
    int graphWidth = graphData.getGraphWidth();
    int graphHeight = graphData.getGraphHeight();
    String imageMapName = graph.getImageMapName();
    String graphURL = callBackURL + (callBackURL.indexOf('?') > -1 ? "&" : "?") + "graphDataId=" + graphDataId;

    sb.append("<div style=\"background-color:white; width:" + graphWidth + "px\">\n");
    sb.append("<div id=\"graphDiv" + imageMapName + "\" style=\"width:" + graphWidth + "px; height:"
            + graphHeight + "px;\">\n");

    if (useImageMap) {
        // write the graph with an image map
        sb.append(graph.getImageMap());//from   w  ww . ja  v  a  2s  .c o  m
        sb.append("<img src=\"" + graphURL + "\" usemap=\"#" + imageMapName + "\" border=\"0\"/>\n");
    } else {
        // just write the graph with the option to turn it into an interactive graph
        sb.append("<img src=\"" + graphURL
                + "\" title=\"Switch to Interactive View\" onclick=\"makeInteractiveGraph('" + callBackURL
                + "', '" + imageMapName + "', '" + graphDataId + "');\" border=\"0\"/>\n");
    }

    sb.append("</div>\n");

    JFreeChart chart = graph.getGraphSource().getChart();
    String graphTitle = chart.getTitle().getText();

    String xAxisLabel = "";
    String yAxisLabel = "";
    double yAxisMin = 0;
    double yAxisMax = 0;

    if (chart.getPlot() instanceof CategoryPlot) {
        CategoryPlot plot = chart.getCategoryPlot();
        xAxisLabel = plot.getDomainAxis().getLabel();
        yAxisLabel = plot.getRangeAxis().getLabel();
        // get the y-axis minimum and maximum range
        yAxisMin = plot.getRangeAxis().getRange().getLowerBound();
        yAxisMax = plot.getRangeAxis().getRange().getUpperBound();
        // get the y-axis minimum and maximum range
        graph.setYAxisMin(yAxisMin);
        graph.setYAxisMax(yAxisMax);
        //set series information for configuration
        graph.setDataSeriesJSON(getDataSeriesJSON(graphData.getLineSetLabels(), graphData.displayAlerts(),
                graphData.displaySeverityAlerts(), "\""));
    }

    //added option to not bring back the button area - cjh
    if (includeButtons) {
        // write the footer
        sb.append("<div style=\"padding:5px; text-align:center;\">\n");
        if (includeFooter) {
            //this keys it to be a timeseries graph so we can do getCategoryPlot
            String dataSeriesJSON = getDataSeriesJSON(graphData.getLineSetLabels(), graphData.displayAlerts(),
                    graphData.displaySeverityAlerts(), "&quot;");

            sb.append(
                    "<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Graph Options\" onclick=\"showTimeSeriesGraphOptions('"
                            + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "', '" + graphTitle
                            + "', '" + xAxisLabel + "', '" + yAxisLabel + "', " + yAxisMin + ", " + yAxisMax
                            + ", '" + dataSeriesJSON + "');\"/>");
            if (graphOptionsHelpLink != null) {
                sb.append(graphOptionsHelpLink);
            }
        }

        sb.append(
                "<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Download\" onclick=\"showDownloadOptions('"
                        + callBackURL + "', '" + imageMapName + "', '" + graphDataId + "');\"/>");

        if (downloadHelpLink != null) {
            sb.append(downloadHelpLink);
        }
        sb.append("</div>\n");
    }
    sb.append("</div>\n");

    if (!useImageMap) {
        sb.append("<div id=\"linkDiv" + imageMapName
                + "\" style=\"font-family: Arial; font-size: 0.7em; text-align: right\">\n");
        sb.append("*Click anywhere on the graph to <a href=\"#\" onclick=\"makeInteractiveGraph('" + callBackURL
                + "', '" + imageMapName + "', '" + graphDataId
                + "'); return false;\">switch to interactive view</a>\n");
        sb.append("</div>\n");
    }
}

From source file:net.sf.jasperreports.chartthemes.spring.EyeCandySixtiesChartTheme.java

@Override
protected void configureChart(JFreeChart jfreeChart, JRChartPlot jrPlot) throws JRException {
    super.configureChart(jfreeChart, jrPlot);

    TextTitle title = jfreeChart.getTitle();
    if (title != null) {
        RectangleInsets padding = title.getPadding();
        double bottomPadding = Math.max(padding.getBottom(), 15d);
        title.setPadding(padding.getTop(), padding.getLeft(), bottomPadding, padding.getRight());
    }// w  ww  . j a  va2  s.  c o  m

    GradientPaint gp = (GradientPaint) getDefaultValue(defaultChartPropertiesMap,
            ChartThemesConstants.BACKGROUND_PAINT);

    jfreeChart.setBackgroundPaint(new GradientPaint(0f, 0f, gp.getColor1(), 0f, getChart().getHeight() * 0.7f,
            gp.getColor2(), false));
}

From source file:ds.monte.carlo.Application.java

private void createGrowthGraph(double[] growthMap) {
    DefaultCategoryDataset growthDataset = new DefaultCategoryDataset();
    double min = 1000000;
    double max = 0;
    int l_100 = growthMap.length;
    int l_40 = (int) Math.round(l_100 * 0.4);
    System.out.print(growthMap.length);
    for (int i = l_40; i < growthMap.length; i++) {
        growthDataset.setValue(growthMap[i], "", "" + i);
        if (growthMap[i] < min) {
            min = growthMap[i];/*from   ww  w.ja v a2s.  c o  m*/
        }
        if (growthMap[i] > max) {
            max = growthMap[i];
        }
    }

    JFreeChart growChart = ChartFactory.createLineChart("Simulated annealing", "", "", growthDataset,
            PlotOrientation.VERTICAL, false, false, false);
    growChart.setBackgroundPaint(Color.WHITE);

    CategoryPlot catPlot = growChart.getCategoryPlot();
    catPlot.setRangeGridlinePaint(new Color(92, 184, 92));

    ValueAxis vAxis = catPlot.getRangeAxis();
    CategoryAxis cAxis = catPlot.getDomainAxis();

    cAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    vAxis.setRange(min, max);

    cAxis.setTickLabelsVisible(false);

    Font font = new Font("SansSerif", Font.PLAIN, 12);
    Font fontTitle = new Font("SansSerif", Font.PLAIN, 14);
    vAxis.setTickLabelFont(font);
    growChart.getTitle().setFont(fontTitle);

    LineAndShapeRenderer renderer = (LineAndShapeRenderer) catPlot.getRenderer();
    Color bootstrapGreen = new Color(92, 184, 92);
    renderer.setSeriesPaint(0, bootstrapGreen);

    ChartPanel chartPanel = new ChartPanel(growChart);
    jPanel6.removeAll();
    jPanel6.add(chartPanel, BorderLayout.CENTER);
    jPanel6.validate();
    //jPanel5.setVisible(true);
}

From source file:msec.org.Tools.java

public static String generateDaysChart(String filename, ArrayList<OneDayValue> data, OneAttrDaysChart chart,
        String title, int duration) {
    if (data.size() == 0) {
        return "data size invalid";
    }/* w w w .  j  a v a2s. c  o  m*/

    int date = Integer.parseInt(data.get(0).getDate());
    GregorianCalendar startgc = new GregorianCalendar(date / 10000, date % 10000 / 100 - 1, date % 100);

    XYDataset xydataset = createDaysDataset(data, startgc, chart);
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title, "time", "", xydataset, true, true, true);

    try {
        XYPlot xyplot = (XYPlot) jfreechart.getPlot();

        //
        DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
        dateaxis.setDateFormatOverride(new SimpleDateFormat("MM/dd"));
        dateaxis.setLabelFont(new Font("", Font.PLAIN, 16)); //
        dateaxis.setLabelPaint(ChartColor.gray);
        dateaxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        dateaxis.setTickLabelPaint(ChartColor.GRAY);

        dateaxis.setMinimumDate(startgc.getTime());
        GregorianCalendar endgc = (GregorianCalendar) startgc.clone();
        endgc.add(GregorianCalendar.DATE, duration);
        dateaxis.setMaximumDate(endgc.getTime());

        dateaxis.setTickMarksVisible(true);
        dateaxis.setTickMarkInsideLength(5);
        dateaxis.setTickUnit(new DateTickUnit(DateTickUnitType.DAY, 1));
        dateaxis.setVerticalTickLabels(true);
        dateaxis.setLabel("");

        //
        ValueAxis rangeAxis = xyplot.getRangeAxis();//?
        rangeAxis.setLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setLabelPaint(ChartColor.gray);
        rangeAxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setTickLabelPaint(ChartColor.gray);
        rangeAxis.setLowerBound(0);

        //
        jfreechart.getLegend().setItemFont(new Font("", Font.PLAIN, 12));
        jfreechart.getLegend().setItemPaint(ChartColor.gray);
        jfreechart.getLegend().setBorder(0, 0, 0, 0);//

        //
        jfreechart.getTitle().setFont(new Font("", Font.PLAIN, 18));//
        jfreechart.getTitle().setPaint(ChartColor.gray);

        //?
        xyplot.setRangeGridlinePaint(ChartColor.GRAY);
        xyplot.setBackgroundPaint(ChartColor.WHITE);
        xyplot.setOutlinePaint(null);//

        int w = 500;
        int h = 300;

        // ChartUtilities.saveChartAsPNG(new File(filename), jfreechart, w, h);
        ChartUtilities.saveChartAsJPEG(new File(filename), 0.8f, jfreechart, w, h);

        return "success";

    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}

From source file:com.ikon.servlet.admin.StatsGraphServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String action = WebUtils.getString(request, "action", "graph");
    String type = WebUtils.getString(request, "t");
    JFreeChart chart = null;
    updateSessionManager(request);//from   ww w . ja  v  a2  s .  co  m

    try {
        if ("refresh".equals(action)) {
            new RepositoryInfo().runAs(null);
            ServletContext sc = getServletContext();
            sc.getRequestDispatcher("/admin/stats.jsp").forward(request, response);
        } else {
            response.setContentType("image/png");
            OutputStream out = response.getOutputStream();

            if (DOCUMENTS.equals(type) || DOCUMENTS_SIZE.equals(type) || FOLDERS.equals(type)) {
                chart = repoStats(type);
            } else if (DISK.equals(type)) {
                chart = diskStats();
            } else if (JVM_MEMORY.equals(type)) {
                chart = jvmMemStats();
            } else if (OS_MEMORY.equals(type)) {
                chart = osMemStats();
            }

            if (chart != null) {
                // Customize title font
                chart.getTitle().setFont(new Font("Tahoma", Font.BOLD, 16));

                // Match body {   background-color:#F6F6EE; }
                chart.setBackgroundPaint(new Color(246, 246, 238));

                // Customize no data
                PiePlot plot = (PiePlot) chart.getPlot();
                plot.setNoDataMessage("No data to display");

                // Customize labels
                plot.setLabelGenerator(null);

                // Customize legend
                LegendTitle legend = new LegendTitle(plot, new ColumnArrangement(), new ColumnArrangement());
                legend.setPosition(RectangleEdge.BOTTOM);
                legend.setFrame(BlockBorder.NONE);
                legend.setItemFont(new Font("Tahoma", Font.PLAIN, 12));
                chart.removeLegend();
                chart.addLegend(legend);

                if (DISK.equals(type) || JVM_MEMORY.equals(type) || OS_MEMORY.equals(type)) {
                    ChartUtilities.writeChartAsPNG(out, chart, 225, 225);
                } else {
                    ChartUtilities.writeChartAsPNG(out, chart, 250, 250);
                }
            }

            out.flush();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}