Line Chart for Emails with JFreeChart


Includes sampling data down to 75 data points

   private byte[] getLineChart(List data, ReportEntity report) throws Exception {
        
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        
        CategoryAxis xAxis = new CategoryAxis();
        NumberAxis yAxis = new NumberAxis();
        List headers = new ArrayList();
        StringTokenizer tokenizer = new StringTokenizer(report.getHeaders(), ",");
        while (tokenizer.hasMoreTokens()) {
            headers.add(tokenizer.nextToken());
        }
        
        if (false && headers.size() > 0) {
            xAxis.setLabel(headers.get(0).toString());
        } else {
            xAxis.setLabel("");
        }
        if (false && headers.size() > 1 && report.getChartColumns() != null) {
            yAxis.setLabel(headers.get(1).toString());
        } else {
            yAxis.setLabel("");
        }
        
        List chartColumns = ChartUtil.getChartColumns(report);
        
        // Reduce data set down to 75 maximum
        double sampleRate = data.size() / 75.0;
        Random random = new Random();
        double countStart = random.nextDouble() * sampleRate;
        int start = (int) Math.round(countStart);
        
        for (Integer column : chartColumns) {
                
            String name = report.getMainTitle();
            if (report.getChartColumns() != null && column.intValue()  25) {
                name = name.substring(0, 25);
            }

            double count = countStart;
            int next = start;
            for (int i = 0; i  1) {
                    if(i != next) {
                        continue;
                    } else {
                        count += sampleRate;
                        next = (int) Math.round(count);
                    }
                }
                
                Double val = 0.0;
                try {
                    val = Double.parseDouble(row[column.intValue()].toString());
                } catch (Exception ex) {}
                
                dataset.addValue(val, name, key);
            }
        }
        
        JFreeChart chart = ChartUtil.createChart(dataset, xAxis, yAxis, report);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        BufferedImage objBufferedImage = chart.createBufferedImage(800, 600, BufferedImage.TYPE_INT_RGB, null);
        ImageIO.write(objBufferedImage, "png", output);
        return output.toByteArray();
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s