Tagged: JFreeChart Toggle Comment Threads | Keyboard Shortcuts

  • Subinkrishna Gopi 12:13 pm on August 6, 2007 Permalink |
    Tags: JFreeChart   

    Creating Pie Charts using JFreeChart with custom colors 

    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.

     
  • Subinkrishna Gopi 7:16 am on July 10, 2007 Permalink |
    Tags: JFreeChart   

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

    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&#91;&#93; byteStream;
    
     fileLength = image.length();
     byteStream = new byte&#91;(int)fileLength&#93;;
     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

     
    • pchopr3 4:52 am on August 27, 2009 Permalink

      Hey Subin,

      Thanks for posting the code. I have a problem:
      I tried using ur code in eclipse after adding jcommon jar files. but the imported library was not found.

      Can u suggest wht can be the issue.

      Thnks,
      PC

    • pchopr3 4:56 am on August 27, 2009 Permalink

      I am using jcommon 1.0.16.jar

    • Subinkrishna G 9:51 am on August 27, 2009 Permalink

      Hi,

      I wrote it almost 2 years back. Then I was using jcommon-1.0.10.jar along with jfreechart-1.0.6.jar, jfreechart-1.0.6-experimental.jar and jfreechart-1.0.6-swt.jar. And I’m not sure whether they’ve changed anything after that. Hope this helps.

      Subin

    • pchopr3 5:37 am on August 28, 2009 Permalink

      okie, i will try with them…thnx

    • kalmud 11:37 am on August 5, 2011 Permalink

      hi Subinkrishna G,
      ur example is nice.
      can u give me code for ScatterPlot in jsp.

      thank u,

  • Subinkrishna Gopi 1:19 pm on July 4, 2007 Permalink |
    Tags: JFreeChart   

    Creating BarCharts with custom colours using JFreeChart 

    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

     
  • Subinkrishna Gopi 5:41 am on July 4, 2007 Permalink |
    Tags: JFreeChart   

    Creating a 3D BarChart using JFreeChart 

    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

     
    • joensson 10:58 am on July 12, 2007 Permalink

      What version of JFreeChart are you using?

      I’m complete new at JFreeChart and have found a ton of examples using the old interface. However I have to use 1.0.6 and the signature of DefaultCategoryDataset setValue is double, Comparable, Comparable – how would you create the chart using 1.0.6?

    • Subin 11:51 am on July 12, 2007 Permalink

      Hi joensson,

      Even I am using JFreeChart 1.0.6. Actually Comaprable is an interface which contains a method specification “public int compareTo(Object o)“. I hope you know what it means. It’s used to compare two different objects.

      String is a class which implements Comparable. We can use any object which is implementing Comparable interface as an argument to the “setValue(double, comparable, comparable);

      I hope this can fix your problem.
      Thank you for visiting my Blog & for the very first comment.

      Subin

  • Subinkrishna Gopi 6:26 am on June 28, 2007 Permalink |
    Tags: JFreeChart   

    Creating Time Series charts using JFreeChart 

    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? )

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel