Example usage for org.jfree.chart ChartFactory createBarChart

List of usage examples for org.jfree.chart ChartFactory createBarChart

Introduction

In this page you can find the example usage for org.jfree.chart ChartFactory createBarChart.

Prototype

public static JFreeChart createBarChart(String title, String categoryAxisLabel, String valueAxisLabel,
        CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) 

Source Link

Document

Creates a bar chart.

Usage

From source file:recomm.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w  w. j av  a2s . c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {

        /* TODO output your page here. You may use following sample code. */

        final String fiat = "FIAT";
        final String audi = "AUDI";
        final String ford = "FORD";
        final String speed = "Speed";
        final String millage = "Millage";
        final String userrating = "User Rating";
        final String safety = "safety";

        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        dataset.addValue(1.0, fiat, speed);
        dataset.addValue(3.0, fiat, userrating);
        dataset.addValue(5.0, fiat, millage);
        dataset.addValue(5.0, fiat, safety);

        dataset.addValue(1.0, audi, speed);
        dataset.addValue(1.0, audi, userrating);
        dataset.addValue(1.0, audi, millage);
        dataset.addValue(1.0, audi, safety);

        dataset.addValue(4.0, ford, speed);
        dataset.addValue(2.0, ford, userrating);
        dataset.addValue(3.0, ford, millage);
        dataset.addValue(6.0, ford, safety);

        JFreeChart barChart = ChartFactory.createBarChart("CAR USAGE STATISTICS", "Category", "Score", dataset,
                PlotOrientation.VERTICAL, true, true, false);

        int width = 640; /* Width of the image */
        int height = 480; /* Height of the image */
        File BarChart = new File("/home/rishabh/###amit/JavaApplication3BarChart.jpeg");
        ChartUtilities.saveChartAsJPEG(BarChart, barChart, width, height);

        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet recomm</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet recomm at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.opensourcestrategies.crmsfa.reports.JFreeCrmsfaCharts.java

/**
 * Lead pipeline.  Description at http://www.opentaps.org/docs/index.php/CRMSFA_Dashboard
 * Note that this counts all the leads in the system for now.
 *//*w  w  w .  j  a v  a  2 s .c  o  m*/
public static String createLeadPipelineChart(Delegator delegator, Locale locale)
        throws GenericEntityException, IOException {
    Map uiLabelMap = UtilMessage.getUiLabels(locale);

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    // get all LEAD statuses that are not CONVERTED, or DEAD
    List<GenericValue> leadStatuses = ReportHelper.findLeadStatusesForDashboardReporting(delegator);

    // report number of leads for each status
    for (GenericValue status : leadStatuses) {
        String statusId = status.getString("statusId");
        long count = delegator.findCountByCondition("PartyAndStatus",
                EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, statusId), null);
        dataset.addValue(count, "", (String) status.get("description", locale));
    }

    // set up the chart
    JFreeChart chart = ChartFactory.createBarChart((String) uiLabelMap.get("CrmLeadPipeline"), null, null,
            dataset, PlotOrientation.HORIZONTAL, false, true, false);
    chart.setBackgroundPaint(Color.white);
    chart.setBorderVisible(true);
    chart.setPadding(new RectangleInsets(5.0, 5.0, 5.0, 5.0));

    // get a reference to the plot for further customisation...
    final CategoryPlot plot = chart.getCategoryPlot();
    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);

    // get the bar renderer to put effects on the bars
    final BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false); // disable bar outlines

    // set up gradient paint on bar
    final GradientPaint gp = new GradientPaint(0.0f, 0.0f, new Color(227, 246, 206), 0.0f, 0.0f,
            new Color(153, 204, 102));
    renderer.setSeriesPaint(0, gp);

    // change the auto tick unit selection to integer units only...
    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // save as a png and return the file name
    return ServletUtilities.saveChartAsPNG(chart, 360, 200, null);
}

From source file:servlet.SalesReportEventsBarChart.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  ww.  j a v  a 2 s.  c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    List<ArrayList> data = productSession.getEventSessionNo();

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    for (int i = 0; i < data.size(); i++) {
        dataset.addValue(Integer.valueOf(data.get(i).get(1).toString()), "Sessions",
                data.get(i).get(0).toString());
    }

    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

    JFreeChart barChart = ChartFactory.createBarChart("No of Sessions", "Event", "Sessions", dataset,
            PlotOrientation.VERTICAL, true, true, false);

    CategoryPlot cplot = (CategoryPlot) barChart.getPlot();
    cplot.setBackgroundPaint(Color.WHITE);//change background color

    //set  bar chart color
    ((BarRenderer) cplot.getRenderer()).setBarPainter(new StandardBarPainter());

    BarRenderer r = (BarRenderer) barChart.getCategoryPlot().getRenderer();
    r.setSeriesPaint(0, Color.GREEN);

    r.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", NumberFormat.getInstance()));
    r.setBaseItemLabelsVisible(true);

    CategoryAxis categoryAxis = cplot.getDomainAxis();
    categoryAxis.setUpperMargin(0.15);

    NumberAxis rangeAxis = (NumberAxis) cplot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setUpperMargin(0.15);

    int width = 550; /* Width of the image */

    int height = 450; /* Height of the image */

    response.setContentType("image/png");
    OutputStream out = response.getOutputStream();

    ChartUtilities.writeChartAsPNG(out, barChart, 400, 300, info);

}

From source file:com.thingsfx.swing.jfreechart.JFreeChartPanel2.java

void initComponents() {

    // create the chart...
    JFreeChart chart = ChartFactory.createBarChart("JFreeChart is Definitely cool!", // chart title
            "Category", // domain axis label
            "Value", // range axis label
            createDataset(), // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips?
            false // URLs?
    );//from w ww. j  a va  2  s .com

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

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

    // get a reference to the plot for further customisation...
    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    // ******************************************************************
    //  More than 150 demo applications are included with the JFreeChart
    //  Developer Guide...for more information, see:
    //
    //  >   http://www.object-refinery.com/jfreechart/guide.html
    //
    // ******************************************************************

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // disable bar outlines...
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);

    // set up gradient paints for series...
    GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64));
    GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, new Color(0, 64, 0));
    GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, new Color(64, 0, 0));
    renderer.setSeriesPaint(0, gp0);
    renderer.setSeriesPaint(1, gp1);
    renderer.setSeriesPaint(2, gp2);

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    // OPTIONAL CUSTOMISATION COMPLETED.

    add(new ChartPanel(chart));
}

From source file:parts.GraphicContent.java

public void setContent(JPanel panel) {
    String sprint[] = null;//from w w  w  . j a  v  a 2s  . co  m
    int taskCount[] = null;
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    try {
        Statement st = scrum.SCRUM.conexao.createStatement();
        String sql = "select COUNT(*) from sprint";
        result = st.executeQuery(sql);
        result.next();
        sprint = new String[result.getInt(1)];
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        Statement st = scrum.SCRUM.conexao.createStatement();
        String sql = "select * from sprint";
        result = st.executeQuery(sql);
        int i = 0;
        while (result.next()) {
            sprint[i] = result.getString("alias");
            i++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    int sprintIDs[] = new int[sprint.length];

    try {
        Statement st = scrum.SCRUM.conexao.createStatement();
        String sql = "select * from sprint";
        result = st.executeQuery(sql);
        int i = 0;
        while (result.next()) {
            sprintIDs[i] = result.getInt("idsprint");
            i++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    for (int i = 0; i < sprint.length; i++) {
        try {
            Statement st = scrum.SCRUM.conexao.createStatement();
            String sql = "select COUNT(*) from sprint_tasks  where idsprint  = " + sprintIDs[i];
            result = st.executeQuery(sql);
            while (result.next()) {
                dataset.addValue(result.getInt(1), "Tarefas", sprint[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    JFreeChart chart = null;
    chart = ChartFactory.createBarChart("Quantidade de tarefas por Sprint", "Sprint", "Tarefas", dataset,
            PlotOrientation.VERTICAL, false, true, false);
    CategoryPlot p = chart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.black);

    ChartPanel cp = new ChartPanel(chart);
    cp.setBounds(0, 0, panel.getWidth(), panel.getHeight());
    panel.removeAll();
    cp.setVisible(true);
    panel.add(cp);
    panel.revalidate();
    panel.repaint();
}

From source file:net.pickapack.chart.BarPlotFrame.java

/**
 * Create a bar plot frame.//from   w w  w.jav  a  2 s  .c o  m
 *
 * @param barPlot the bar plot
 * @param domainAxisLabel the domain axis label
 * @param width the width
 * @param height the height
 */
public BarPlotFrame(BarPlot<ItemT> barPlot, String domainAxisLabel, int width, int height) {
    super(barPlot.getTitle());

    DefaultCategoryDataset dataSet = new DefaultCategoryDataset();

    for (ItemT item : barPlot.getItems()) {
        if (barPlot.getPredicate().apply(item)) {
            for (SubBarPlot<ItemT> subBarPlot : barPlot.getSubBarPlots()) {
                dataSet.addValue(subBarPlot.getGetValueCallback().apply(item), subBarPlot.getTitle(),
                        subBarPlot.getGetTitleCallback().apply(item));
            }
        }
    }

    JFreeChart chart = barPlot.isStacked()
            ? ChartFactory.createStackedBarChart(barPlot.getTitle(), domainAxisLabel, barPlot.getTitleY(),
                    dataSet, PlotOrientation.VERTICAL, true, true, false)
            : ChartFactory.createBarChart(barPlot.getTitle(), domainAxisLabel, barPlot.getTitleY(), dataSet,
                    PlotOrientation.VERTICAL, true, true, false);

    CategoryPlot plot = chart.getCategoryPlot();

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    ChartPanel chartPanel = new ChartPanel(chart, false);
    chartPanel.setPreferredSize(new Dimension(width, height));
    chartPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    setContentPane(chartPanel);
}

From source file:datavis.BarGraph.java

public JFreeChart getChartPanel() {
    JFreeChart chart = ChartFactory.createBarChart(getBarGraphName(), getIntervalTypeName(),
            getNumberTypeName(), getBarGraph(), PlotOrientation.VERTICAL, true, true, false);
    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.darkGray);
    plot.setDomainGridlinePaint(new Color(240, 180, 180));
    plot.setRangeGridlinePaint(new Color(240, 180, 180));

    final BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setBarPainter(new StandardBarPainter());

    final GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, new Color(170, 240, 240), 0.0f, 0.0f,
            new Color(170, 240, 240));

    renderer.setSeriesPaint(0, gp0);//from  w  ww  .j  a  v  a 2s. co  m

    final CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));

    return chart;
}

From source file:org.operamasks.faces.render.graph.BarChartRenderer.java

protected JFreeChart createChart(UIChart comp) {
    Dataset dataset = createDataset(comp);
    JFreeChart chart = null;/* w w  w  . j  a va 2  s  . co  m*/

    if (dataset instanceof CategoryDataset) {
        if (comp.isStacked()) {
            if (comp.isEffect3D()) {
                chart = ChartFactory.createStackedBarChart3D(null, null, null, (CategoryDataset) dataset,
                        getChartOrientation(comp), false, false, false);
            } else {
                chart = ChartFactory.createStackedBarChart(null, null, null, (CategoryDataset) dataset,
                        getChartOrientation(comp), false, false, false);
            }
        } else {
            if (comp.isEffect3D()) {
                chart = ChartFactory.createBarChart3D(null, null, null, (CategoryDataset) dataset,
                        getChartOrientation(comp), false, false, false);
            } else {
                chart = ChartFactory.createBarChart(null, null, null, (CategoryDataset) dataset,
                        getChartOrientation(comp), false, false, false);
            }
        }
    } else if (dataset instanceof IntervalXYDataset) {
        chart = ChartFactory.createXYBarChart(null, null, (dataset instanceof TimeSeriesCollection), null,
                (IntervalXYDataset) dataset, getChartOrientation(comp), false, false, false);
    }

    return chart;
}

From source file:com.liferay.portlet.polls.action.ViewChartAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    try {// ww  w. j a  v a 2  s  . com
        ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

        long questionId = ParamUtil.getLong(request, "questionId");

        String chartType = ParamUtil.getString(request, "chartType", "pie");

        CategoryDataset dataset = PollsUtil.getVotesDataset(questionId);

        String chartName = themeDisplay.translate("vote-results");
        String xName = themeDisplay.translate("choice");
        String yName = themeDisplay.translate("votes");

        JFreeChart chart = null;

        if (chartType.equals("area")) {
            chart = ChartFactory.createAreaChart(chartName, xName, yName, dataset, PlotOrientation.VERTICAL,
                    true, false, false);
        } else if (chartType.equals("horizontal_bar")) {
            chart = ChartFactory.createBarChart(chartName, xName, yName, dataset, PlotOrientation.HORIZONTAL,
                    true, false, false);
        } else if (chartType.equals("line")) {
            chart = ChartFactory.createLineChart(chartName, xName, yName, dataset, PlotOrientation.VERTICAL,
                    true, false, false);
        } else if (chartType.equals("vertical_bar")) {
            chart = ChartFactory.createBarChart(chartName, xName, yName, dataset, PlotOrientation.VERTICAL,
                    true, false, false);
        } else {
            PieDataset pieData = DatasetUtilities.createPieDatasetForRow(dataset, 0);

            chart = ChartFactory.createPieChart(chartName, pieData, true, false, false);
        }

        response.setContentType(ContentTypes.IMAGE_JPEG);

        OutputStream os = response.getOutputStream();

        ChartUtilities.writeChartAsJPEG(os, chart, 400, 400);

        return null;
    } catch (Exception e) {
        PortalUtil.sendError(e, request, response);

        return null;
    }
}

From source file:it.marcoberri.mbmeteo.action.chart.GetLastTBar.java

/**
 * Processes requests for both HTTP/*from w  ww . jav  a 2 s . c om*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);

    Meteolog meteolog = ds.find(Meteolog.class).order("-time").limit(1).get();

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.addValue(meteolog.getOutdoorTemperature(), ChartEnumMinMaxHelper.outdoorTemperatureMin.getUm(),
            DateTimeUtil.dateFormat("yyyy-MM-dd hh:mm:ss", meteolog.getTime()));

    final JFreeChart chart = ChartFactory.createBarChart("T", // chart title
            "", // domain axis label
            "", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            false, // tooltips?
            false // URLs?
    );

    final CategoryPlot xyPlot = (CategoryPlot) chart.getPlot();

    xyPlot.getRangeAxis().setRange(0, meteolog.getOutdoorTemperature() + 2);
    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    response.setContentType("image/jpeg");
    response.setHeader("Content-Length", "" + f.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
    final OutputStream out = response.getOutputStream();
    final FileInputStream in = new FileInputStream(f.toString());
    final int size = in.available();
    final byte[] content = new byte[size];
    in.read(content);
    out.write(content);
    in.close();
    out.close();

}