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:it.marcoberri.mbmeteo.action.chart.GetMinOrMax.java

/**
 *
 * @param request//from   w  w w . j  a  v a  2  s  .c  om
 * @param response
 * @throws ServletException
 * @throws IOException
 */
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);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");
    final String period = Default.toString(params.get("period"), "day");
    final String type = Default.toString(params.get("type"), "min");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {

        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {
                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (Exception e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final Query q = ds.createQuery(MapReduceMinMax.class).disableValidation();
    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    final String formatIn = getFormatIn(period);
    final String formatOut = getFormatOut(period);

    final List<Date> datesIn = getRangeDate(dFrom, dTo);
    final HashSet<String> datesInString = new HashSet<String>();

    for (Date d : datesIn) {
        datesInString.add(DateTimeUtil.dateFormat(formatIn, d));
    }

    if (datesIn != null && !datesIn.isEmpty()) {
        q.filter("_id in", datesInString);
    }
    q.order("_id");

    final List<MapReduceMinMax> mapReduceResult = q.asList();

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    ChartEnumMinMaxHelper chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, type);

    for (MapReduceMinMax m : mapReduceResult) {
        try {
            final Date tmpDate = DateTimeUtil.getDate(formatIn, m.getId().toString());

            if (tmpDate == null) {
                continue;
            }

            final Method method = m.getClass().getMethod(chartEnum.getMethod());
            final Number n = (Number) method.invoke(m);
            dataset.addValue(n, chartEnum.getType(), DateTimeUtil.dateFormat(formatOut, tmpDate));

        } catch (IllegalAccessException ex) {
            log.error(ex);
        } catch (IllegalArgumentException ex) {
            log.error(ex);
        } catch (InvocationTargetException ex) {
            log.error(ex);
        } catch (NoSuchMethodException ex) {
            log.error(ex);
        } catch (SecurityException ex) {
            log.error(ex);
        }
    }

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

    final CategoryPlot xyPlot = (CategoryPlot) chart.getPlot();
    final CategoryAxis domain = xyPlot.getDomainAxis();

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        xyPlot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    } else {
        xyPlot.getRangeAxis().setAutoRange(true);
    }

    domain.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    try {

        if (cacheWriteEnable) {
            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        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();
    } catch (Exception e) {
        log.error(e);
    } finally {
        boolean delete = f.delete();
    }

}

From source file:edu.ucla.stat.SOCR.chart.demo.LayeredBarChartDemo2.java

protected JFreeChart createLegend(CategoryDataset dataset) {

    //  JFreeChart chart = ChartFactory.createAreaChart(
    JFreeChart chart = ChartFactory.createBarChart(chartTitle, // chart title
            domainLabel, // domain axis label
            rangeLabel, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );//  www .  java2s . com

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = chart.getCategoryPlot();

    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    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);
    // renderer.setDrawOutlines(true);
    // renderer.setUseFillPaint(true);
    // renderer.setFillPaint(Color.white);
    renderer.setLegendItemLabelGenerator(new SOCRCategorySeriesLabelGenerator());
    return chart;

}

From source file:org.datacleaner.widgets.result.ValueDistributionResultSwingRendererGroupDelegate.java

public JSplitPane renderGroupResult(final ValueCountingAnalyzerResult result) {
    final Integer distinctCount = result.getDistinctCount();
    final Integer unexpectedValueCount = result.getUnexpectedValueCount();
    final int totalCount = result.getTotalCount();

    _valueCounts = result.getReducedValueFrequencies(_preferredSlices);
    _valueCounts = moveUniqueToEnd(_valueCounts);

    for (ValueFrequency valueCount : _valueCounts) {
        setDataSetValue(valueCount.getName(), valueCount.getCount());
    }/*from www  .j  a  va  2 s  . c o  m*/

    logger.info("Rendering with {} slices", getDataSetItemCount());
    drillToOverview(result);

    // chart for display of the dataset
    String title = "Value distribution of " + _groupOrColumnName;
    final JFreeChart chart = ChartFactory.createBarChart(title, "Value", "Count", _dataset,
            PlotOrientation.HORIZONTAL, true, true, false);

    List<Title> titles = new ArrayList<Title>();
    titles.add(new ShortTextTitle("Total count: " + totalCount));
    if (distinctCount != null) {
        titles.add(new ShortTextTitle("Distinct count: " + distinctCount));
    }
    if (unexpectedValueCount != null) {
        titles.add(new ShortTextTitle("Unexpected value count: " + unexpectedValueCount));
    }
    chart.setSubtitles(titles);

    ChartUtils.applyStyles(chart);

    // code-block for tweaking style and coloring of chart
    {
        final CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.getDomainAxis().setVisible(false);

        int colorIndex = 0;
        for (int i = 0; i < getDataSetItemCount(); i++) {
            final String key = getDataSetKey(i);
            final Color color;
            final String upperCaseKey = key.toUpperCase();
            if (_valueColorMap.containsKey(upperCaseKey)) {
                color = _valueColorMap.get(upperCaseKey);
            } else {
                if (i == getDataSetItemCount() - 1) {
                    // the last color should not be the same as the first
                    if (colorIndex == 0) {
                        colorIndex++;
                    }
                }

                Color colorCandidate = SLICE_COLORS[colorIndex];
                int darkAmount = i / SLICE_COLORS.length;
                for (int j = 0; j < darkAmount; j++) {
                    colorCandidate = WidgetUtils.slightlyDarker(colorCandidate);
                }
                color = colorCandidate;

                colorIndex++;
                if (colorIndex >= SLICE_COLORS.length) {
                    colorIndex = 0;
                }
            }

            plot.getRenderer().setSeriesPaint(i, color);
        }
    }

    final ChartPanel chartPanel = ChartUtils.createPanel(chart, false);

    final DCPanel leftPanel = new DCPanel();
    leftPanel.setLayout(new VerticalLayout());
    leftPanel.add(WidgetUtils.decorateWithShadow(chartPanel));

    _backButton.setMargin(new Insets(0, 0, 0, 0));
    _backButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            drillToOverview(result);
        }
    });

    _rightPanel.setLayout(new VerticalLayout());
    _rightPanel.add(_backButton);
    _rightPanel.add(WidgetUtils.decorateWithShadow(_table.toPanel()));

    final JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    split.setOpaque(false);
    split.add(leftPanel);
    split.add(_rightPanel);
    split.setDividerLocation(550);

    return split;
}

From source file:userinterface.AdminRole.DataAnalysisJPanel.java

private void donorGenderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_donorGenderButtonActionPerformed
    // TODO add your handling code here:
    int m = 0, f = 0;

    for (Organization org : enterprise.getOrganizationDirectory().getOrganizationList()) {
        if (org instanceof DonorOrganization) {
            for (Donor donor : org.getDonorDirectory().getDonorList()) {

                if (donor.getGender().equalsIgnoreCase("male")) {
                    m++;//from  w ww.  ja v a  2s . c o  m
                }
                if (donor.getGender().equalsIgnoreCase("female")) {
                    f++;
                }
            }
        }
    }
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.setValue(m, "Number", "Male");
    dataset.setValue(f, "Number", "Female");

    JFreeChart chart = ChartFactory.createBarChart("Donors", "Gender", "Number", dataset,
            PlotOrientation.VERTICAL, false, true, false);
    CategoryPlot p = chart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.black);

    ChartFrame frame = new ChartFrame("Availability Bar Chart", chart);

    frame.setVisible(true);
    frame.setSize(450, 500);

    //       panel.removeAll();
    //        panel.add(frame, BorderLayout.CENTER);
    //        panel.validate();
}

From source file:fr.crnan.videso3d.ihm.PLNSPanel.java

private JToolBar createToolbar() {
    JToolBar toolbar = new JToolBar();

    JButton newGraph = new JButton("Nouveau");
    newGraph.addActionListener(new ActionListener() {

        @Override/*w ww.ja  va 2  s  .co m*/
        public void actionPerformed(ActionEvent e) {
            PLNSChartCreateUI chartCreator = new PLNSChartCreateUI(PLNSPanel.this);
            JFreeChart chart = null;
            try {
                if (chartCreator.showDialog(PLNSPanel.this)) {
                    switch (chartCreator.getChartType()) {
                    case 0://XY
                        JDBCXYDataset dataset = new JDBCXYDataset(plnsAnalyzer.getConnection());
                        dataset.executeQuery(chartCreator.getRequest());
                        chart = ChartFactory.createXYAreaChart(chartCreator.getChartTitle(),
                                chartCreator.getAbscissesTitle(), chartCreator.getOrdonneesTitle(), dataset,
                                PlotOrientation.VERTICAL, false, true, false);
                        break;
                    case 1://Pie
                        JDBCPieDataset dataset1 = new JDBCPieDataset(plnsAnalyzer.getConnection());
                        dataset1.executeQuery(chartCreator.getRequest());
                        chart = ChartFactory.createPieChart3D(chartCreator.getChartTitle(), dataset1, false,
                                true, false);
                        break;
                    case 2://Category
                        JDBCCategoryDataset dataset2 = new JDBCCategoryDataset(plnsAnalyzer.getConnection());
                        dataset2.executeQuery(chartCreator.getRequest());
                        chart = ChartFactory.createBarChart(chartCreator.getChartTitle(),
                                chartCreator.getAbscissesTitle(), chartCreator.getOrdonneesTitle(), dataset2,
                                PlotOrientation.VERTICAL, false, true, false);
                        break;
                    default:
                        break;
                    }
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
                JOptionPane.showMessageDialog(PLNSPanel.this,
                        "<html>L'excution de la requte a chou :<br />" + e1 + "</html>",
                        "Impossible de crer le graphique", JOptionPane.ERROR_MESSAGE);
            }
            if (chart != null)
                addChart(chart);

        }
    });

    toolbar.add(newGraph);

    JButton retile = new JButton("Rarranger");
    retile.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            desktop.tile(true);
        }
    });
    toolbar.add(retile);

    return toolbar;
}

From source file:br.com.OCTur.view.InfograficoController.java

private BufferedImage receitaMensal() {
    DefaultCategoryDataset dcdDados = new DefaultCategoryDataset();
    Calendar inicio = Calendar.getInstance();
    System.out.println(this.inicio);
    inicio.setTime(this.inicio);
    MAIOR = 0;/*from   w  w  w  . j  a va  2 s . co  m*/
    while (inicio.getTime().before(fim)) {
        Calendar mes = Calendar.getInstance();
        mes.setTime(inicio.getTime());
        mes.add(Calendar.MONTH, 1);
        List<Reserva> reservas = new ReservaDAO().pegarPorHotelInicioFim(hotel, inicio.getTime(),
                mes.getTime());
        double total = 0;
        for (Reserva reserva : reservas) {
            long dias = (reserva.getFim().getTime() - reserva.getInicio().getTime()) / 1000 / 60 / 60 / 24;
            if (dias <= 0) {
                dias = 1;
            }
            total += (reserva.getQuarto().getOrcamento().getPreco() * dias);
        }
        if (total > MAIOR) {
            MAIOR = total;
            this.mes = DateFormatter.toFullMonthName(inicio.getTime());
        }
        dcdDados.addValue(total, "Receita", DateFormatter.toMonthName(inicio.getTime()));
        inicio.add(Calendar.MONTH, 1);
    }
    JFreeChart jFreeChart = ChartFactory.createBarChart("", "", "", dcdDados, PlotOrientation.VERTICAL, false,
            false, false);
    return jFreeChart.createBufferedImage(555, 170);
}

From source file:net.sourceforge.subsonic.controller.FolderChartController.java

private JFreeChart createChart(CategoryDataset dataset, HttpServletRequest request) {
    JFreeChart chart = ChartFactory.createBarChart(null, null, null, dataset, PlotOrientation.HORIZONTAL, false,
            false, false);// w  ww .  j ava  2s .co  m
    CategoryPlot plot = chart.getCategoryPlot();
    Paint background = new GradientPaint(0, 0, Color.lightGray, 0, IMAGE_MIN_HEIGHT, Color.white);
    plot.setBackgroundPaint(background);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.gray);
    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);

    LogarithmicAxis rangeAxis = new LogarithmicAxis(null);
    rangeAxis.setStrictValuesFlag(false);
    rangeAxis.setAllowNegativesFlag(true);
    //        rangeAxis.setTickUnit(new NumberTickUnit(.1, new DecimalFormat("##0%")));
    plot.setRangeAxis(rangeAxis);

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

    // Set up gradient paint for series.
    GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.gray, 0.0f, 0.0f, new Color(0, 0, 64));
    renderer.setSeriesPaint(0, gp0);

    renderer.setBaseItemLabelsVisible(true);
    renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    renderer.setBaseItemLabelFont(new Font("SansSerif", Font.BOLD, 11));
    renderer.setItemLabelAnchorOffset(-45.0);

    renderer.setSeriesItemLabelPaint(0, Color.white);
    renderer.setBaseItemLabelPaint(Color.white);

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

    // Set theme-specific colors.
    Color bgColor = getBackground(request);
    Color fgColor = getForeground(request);

    chart.setBackgroundPaint(bgColor);

    domainAxis.setTickLabelPaint(fgColor);
    domainAxis.setTickMarkPaint(fgColor);
    domainAxis.setAxisLinePaint(fgColor);

    rangeAxis.setTickLabelPaint(fgColor);
    rangeAxis.setTickMarkPaint(fgColor);
    rangeAxis.setAxisLinePaint(fgColor);

    return chart;
}

From source file:org.talend.dataprofiler.chart.TOPChartService.java

@Override
public Object createBenfordChartByKCD(String axisXLabel, String categoryAxisLabel, Object dataset,
        Object customerDataset, List<String> dotChartLabels, double[] formalValues, String title) {
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    Object barChart = ChartFactory.createBarChart(null, axisXLabel, categoryAxisLabel,
            (CategoryDataset) dataset, PlotOrientation.VERTICAL, false, true, false);
    Object lineChart = ChartDecorator.decorateBenfordLawChartByKCD((CategoryDataset) dataset, customerDataset,
            (JFreeChart) barChart, title, categoryAxisLabel, dotChartLabels, formalValues);
    return lineChart;

}

From source file:net.sourceforge.processdash.ui.web.reports.analysis.Report5.java

private JFreeChart createBarChart() {
    JFreeChart chart = null;/*from   w  w  w  . j av a 2  s.  c o  m*/
    if (get3DSetting()) {
        chart = ChartFactory.createBarChart3D(null, null, null, data.catDataSource(), PlotOrientation.VERTICAL,
                false, true, false);
        chart.getPlot().setForegroundAlpha(ALPHA);

    } else {
        chart = ChartFactory.createBarChart(null, null, null, data.catDataSource(), PlotOrientation.VERTICAL,
                false, true, false);
    }

    setupCategoryChart(chart);
    return chart;
}

From source file:com.rapidminer.gui.viewer.metadata.model.NominalAttributeStatisticsModel.java

/**
 * Creates the histogram chart.// w  ww .jav  a  2 s.c o  m
 * 
 * @return
 */
private JFreeChart createBarChart() {
    JFreeChart chart = ChartFactory.createBarChart(null, null, null, createBarDataset(),
            PlotOrientation.VERTICAL, false, false, false);
    AbstractAttributeStatisticsModel.setDefaultChartFonts(chart);
    chart.setBackgroundPaint(null);
    chart.setBackgroundImageAlpha(0.0f);

    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setRangeGridlinesVisible(false);
    plot.setDomainGridlinesVisible(false);
    plot.setOutlineVisible(false);
    plot.setRangeZeroBaselineVisible(false);
    plot.setDomainGridlinesVisible(false);
    plot.setBackgroundPaint(COLOR_INVISIBLE);
    plot.setBackgroundImageAlpha(0.0f);

    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setSeriesPaint(0, AttributeGuiTools.getColorForValueType(Ontology.NOMINAL));
    renderer.setBarPainter(new StandardBarPainter());
    renderer.setDrawBarOutline(true);
    renderer.setShadowVisible(false);

    return chart;
}