a cup of java

Here’s your cup of hot java & web 2.0 cookies. Enjoy it.

Posts Tagged ‘JFreeChart

Creating Pie Charts using JFreeChart with custom colors

without comments

I have attached a sample code snippet for creating a Pie Chart using JFreeChart with custom colors. There is a PieReneder (a static inner class) which can be used to achieve the same. The PieRenderer takes an array of java.awt.Color in its constructor.

package subin.rnd.chart;
import java.awt.Color;
import java.io.File;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
public class PieChartWithCustomColours
{
    public static void main(String[] args)
    {
        DefaultPieDataset dataset = new DefaultPieDataset();
        JFreeChart chart;
       
        // Defining the dataset
        dataset.setValue("Windows", 60);
        dataset.setValue("Linux", 20);
        dataset.setValue("Mac", 10);
        dataset.setValue("Unix", 5);
        dataset.setValue("DOS", 5);
       
        chart = ChartFactory.createPieChart(
                "OS Chart", dataset, false, false, false);
       
        PiePlot plot = (PiePlot)chart.getPlot();
       
        // Specify the colors here
        Color[] colors = {Color.blue, Color.yellow, Color.green};
        PieRenderer renderer = new PieRenderer(colors);
        renderer.setColor(plot, dataset);
       
        try
        {
            // This will create a PNG image
            ChartUtilities.saveChartAsPNG(new File("chart.png"), chart, 400,
                    220);
        }
        catch (Exception e)
        {
            System.out.println("Exception while creating the chart");
        }
    }
   
   
    /*
     * A simple renderer for setting custom colors
     * for a pie chart.
     */
   
    public static class PieRenderer
    {
        private Color[] color;
       
        public PieRenderer(Color[] color)
        {
            this.color = color;
        }       
       
        public void setColor(PiePlot plot, DefaultPieDataset dataset)
        {
            List <Comparable> keys = dataset.getKeys();
            int aInt;
           
            for (int i = 0; i < keys.size(); i++)
            {
                aInt = i % this.color.length;
                plot.setSectionPaint(keys.get(i), this.color[aInt]);
            }
        }
    }
}

Sample Output

Pie Chart With Custom Colors (JFreeChart)

Here the colors are repeating, right? Its b’ coz there is only three entries in the input color array to the PieRenderer.

Written by Subinkrishna G

August 6, 2007 at 12:13 pm

Posted in Code Snippets, Graphics

Tagged with

Displaying dynamic charts in a web page (using JFreeChart & JSP)

with 4 comments

This code snippet will tell you how to create a chart (using JFreeChart) on the fly and displaying it in a webpage.

getChart.jsp

< %@ page import="java.io.*" %>
< %@ page import="org.jfree.chart.JFreeChart" %>
< %@ page import="org.jfree.chart.ChartUtilities" %>

< %
 try
 {
 File image = File.createTempFile("image", "tmp");

 // Assume that we have the chart
 ChartUtilities.saveChartAsPNG(image, chart, 500, 300);

 FileInputStream fileInStream = new FileInputStream(image);
 OutputStream outStream = response.getOutputStream();   

 long fileLength;
 byte[] byteStream;

 fileLength = image.length();
 byteStream = new byte[(int)fileLength];
 fileInStream.read(byteStream, 0, (int)fileLength);

 response.setContentType("image/png");
 response.setContentLength((int)fileLength);
 response.setHeader("Cache-Control",
     "no-store,no-cache, must-revalidate, post-check=0, pre-check=0");
 response.setHeader("Pragma", "no-cache");

 fileInStream.close();
 outStream.write(byteStream);
 outStream.flush();
 outStream.close();

 }
 catch (IOException e)
 {
 System.err.println("Problem occurred creating chart.");
 }

%>

How to use it in a webpage:

<img src="getChart.jsp" alt="Progress chart" />

We can make it more dynamic using various parameters. See the sample below.

<img src="getChart.jsp?type=bar&action=showProfits" alt="Progress chart" />

Useful links: creating charts using JFreeChart
Creating BarChart with custom colors using JFreeChart
Creating a 3D BarChart using JFreeChart
Creating Time Series charts using JFreeChart
Creating Pie Chart using JFreeChart (Using plot)
Creating Pie Chart using JFreeChart

Written by Subinkrishna G

July 10, 2007 at 7:16 am

Posted in Code Snippets, Graphics, JSP, Tips, Web

Tagged with

Creating BarCharts with custom colours using JFreeChart

without comments

This can be achieved by extending the BarRenderer. BarRenderer is responsible for all kind of UI related things like setting the font, setting the colors, setting the alignment etc etc. Rather we can say everything. The same can be achieved by extending corresponding renderer.

Here the getItemPaint(row, col) has been overridden to achieve the custom colors.

CustomRenderer:

import org.jfree.chart.renderer.category.BarRenderer;
import java.awt.Color;
import java.awt.Paint;
class CustomRenderer extends BarRenderer
{
 private Paint[] colors;
 public CustomRenderer()
 {
    this.colors = new Paint[] {Color.red, Color.blue, Color.green,
      Color.yellow, Color.orange, Color.cyan,
      Color.magenta, Color.blue};
 }
 public Paint getItemPaint(final int row, final int column)
 {
    // returns color for each column
    return (this.colors[column % this.colors.length]);
 }
}
 

Using custom renderer with the CategoryPlot:

final JFreeChart chart = ChartFactory.createBarChart(
   "chart title",
   "x axis label",
   "y axis label ",
   dataset,
   PlotOrientation.VERTICAL,
   false,                
   true,
   false
);
chart.setBackgroundPaint(Color.lightGray);
// get a reference to the plot for further customisation...
final CategoryPlot plot = chart.getCategoryPlot();
CategoryItemRenderer renderer = new CustomRenderer();
plot.setRenderer(renderer);
 

Other useful links:
Creating a 3D BarChart using JFreeChart
Creating Time Series charts using JFreeChart
Creating Pie Chart using JFreeChart (Using plot)
Creating Pie Chart using JFreeChart

Written by Subinkrishna G

July 4, 2007 at 1:19 pm

Posted in Code Snippets, Graphics

Tagged with

Creating a 3D BarChart using JFreeChart

with 2 comments

The given code snippet can create a 3D Bar Chart. The given Bar Chart compares 2 aspects of each customer. The generated chart will have two bars for each customer for both Profit1 and Profit 2 (see the dataset).

Profit 1 can can be total annual profit and Profit 2 can be profit for a particular period like monthly or weekly profit. Please find the sample image created using this code.

DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.setValue(6, "Profit1", "Jane");
dataset.setValue(3, "Profit2", "Jane");
dataset.setValue(7, "Profit1", "Tom");
dataset.setValue(10, "Profit2", "Tom");
dataset.setValue(8, "Profit1", "Jill");
dataset.setValue(8, "Profit2", "Jill");
dataset.setValue(5, "Profit1", "John");
dataset.setValue(6, "Profit2", "John");
dataset.setValue(12, "Profit1", "Fred");
dataset.setValue(5, "Profit2", "Fred");
// Profit1, Profit2 represent the row keys
// Jane, Tom, Jill, etc. represent the column keys
JFreeChart chart = ChartFactory.createBarChart3D(
   "Comparison between Salesman",  // Chart name
   "Salesman",                     // X axis label
   "Value ($)",                    // Y axis value
   dataset,                        // data set
   PlotOrientation.VERTICAL,
   true, true, false);
// Creating a JPEG image
try
{
   ChartUtilities.saveChartAsJPEG(new File("myChart.jpg"), chart, 500, 300);
}
catch (IOException e)
{
   System.err.println("Problem occurred creating chart.");
}

Image generated:

3d BarChart Generated using JFreeChart

Other useful links:
Creating Time Series charts using JFreeChart
Creating Pie Chart using JFreeChart (Using plot)
Creating Pie Chart using JFreeChart

Written by Subinkrishna G

July 4, 2007 at 5:41 am

Posted in Code Snippets, Graphics

Tagged with

Creating Time Series charts using JFreeChart

without comments

I have attached a code snippet which can give you a basic idea on creating a time-series chart using JFreeChart. This is a part of JFreeChart samples which come along with the free distribution of JFreeChart.

// Creating a dataset
TimeSeries s1 = new TimeSeries("Name of the Time series", Month.class);
s1.add(new Month(2, 2001), 181.8);
s1.add(new Month(3, 2001), 167.3);
s1.add(new Month(4, 2001), 153.8);
s1.add(new Month(5, 2001), 167.6);
s1.add(new Month(6, 2001), 158.8);
s1.add(new Month(7, 2001), 148.3);
// Creating the chart
JFreeChart chart = ChartFactory.createTimeSeriesChart(
  "Title of the chart", // title
  "X axis value",        // x-axis label
  "Y axis value",        // y-axis label
  dataset,                // data
  true,                    // create legend?
  true,                    // generate tooltips?
  false                    // generate URLs?);
// Setting the chart properties
chart.setBackgroundPaint(Color.white);
// Setting the plot properties
XYPlot plot = (XYPlot) chart.getPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
XYItemRenderer r = plot.getRenderer();
if (r instanceof XYLineAndShapeRenderer)
{
     XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
     renderer.setDefaultShapesVisible(true);
     renderer.setDefaultShapesFilled(true);
}
DateAxis axis = (DateAxis) plot.getDomainAxis();axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
return (chart);

Online JFreeChart Demo (Java WebStart)
(What is Java WebStart Technology? )

Written by Subinkrishna G

June 28, 2007 at 6:26 am

Posted in Code Snippets, Graphics

Tagged with