Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Saturday, 6 July 2013

Charts with JFreeChart 1

JFreeChart is a free Java chart library that can be used to display charts from Java applications. It features:
  • A wide range of chart types
  • support for many output types, including Swing components, image files (including PNG and JPEG), and vector graphics file formats (including PDF, EPS and SVG);
  • It is distributed under the terms of the LGPL, which permits use in proprietary applications.
In this post, I will describe how to use JFreeChart to display a comparative barchart, with data that contains multiple series which have to be grouped (G1, G2) per date. This effectively gives three levels of information (series, group and date). In order to display this data in a chart, we can use a StackedBarChart from JFreeChart. Please note that this is a result of my playing around with JFreeChart, and is not from the official documentation, which means that some of my assumptions may not be accurate. Follow these steps to run the example
  1. Download JFreeChart from here.
  2. Create the DataSet: The StakedBarChart takes a CategoryDataset as input. The following piece of code shows how to add data to the CategoryDataset.
      DefaultCategoryDataset dataSet = new DefaultCategoryDataset();

    dataSet.addValue(100, "Series1 G1", "Jan 04");
    dataSet.addValue(150, "Series1 G2", "Jan 04");
    It is important to note that the order in which you add data to the Dataset, as this would affect how you assign colors to the different series.
  3. Create the renderer and assign series colors:
      GroupedStackedBarRenderer renderer = new GroupedStackedBarRenderer();
    renderer.setItemMargin(0.01);
    renderer.setDrawBarOutline(false);

    renderer.setSeriesPaint(0, Color.blue);
    renderer.setSeriesPaint(1, Color.blue);
    The order of the series in the Dataset, will dictate series number when assigning colors. You will see this in the full code shown below.
  4. Map series to groups: This is done using the KeyToGroupMap.
      KeyToGroupMap keytogroupmap = new KeyToGroupMap("G1");
    keytogroupmap.mapKeyToGroup("Series1 G1", "G1");
    keytogroupmap.mapKeyToGroup("Series2 G1", "G1");
  5. Create the Legend: Since I wanted to give same color to a given series in different groups, I had to add a legend collection that maps colors to the series
     private static LegendItemCollection createLegendItems() {
    LegendItemCollection legenditemcollection = new LegendItemCollection();
    LegendItem legenditem = new LegendItem("Series1", "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, Color.blue);
    LegendItem legenditem1 = new LegendItem("Series2", "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, Color.cyan);
    LegendItem legenditem2 = new LegendItem("Series3", "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, Color.green);
    LegendItem legenditem3 = new LegendItem("Series4", "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, Color.yellow);
    legenditemcollection.add(legenditem);
    legenditemcollection.add(legenditem1);
    legenditemcollection.add(legenditem2);
    legenditemcollection.add(legenditem3);
    return legenditemcollection;
    }
  6. The code
    package chart;

    import java.awt.Color;

    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartFrame;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.LegendItem;
    import org.jfree.chart.LegendItemCollection;
    import org.jfree.chart.axis.SubCategoryAxis;
    import org.jfree.chart.plot.CategoryPlot;
    import org.jfree.chart.plot.Plot;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.renderer.category.GroupedStackedBarRenderer;
    import org.jfree.data.KeyToGroupMap;
    import org.jfree.data.category.CategoryDataset;
    import org.jfree.data.category.DefaultCategoryDataset;

    public class StackedBarChartTest {

    private static CategoryDataset getData() {
    DefaultCategoryDataset dataSet = new DefaultCategoryDataset();

    dataSet.addValue(100, "Series1 G1", "Jan 04");
    dataSet.addValue(150, "Series1 G2", "Jan 04");

    dataSet.addValue(60, "Series2 G1", "Feb 04");
    dataSet.addValue(90, "Series2 G2", "Feb 04");

    dataSet.addValue(70, "Series3 G2", "Feb 04");
    dataSet.addValue(99, "Series3 G1", "Feb 04");

    dataSet.addValue(100, "Series4 G1", "Feb 04");
    dataSet.addValue(80, "Series4 G2", "Feb 04");

    dataSet.addValue(20, "Series1 G1", "Feb 04");
    dataSet.addValue(50, "Series1 G2", "Feb 04");

    dataSet.addValue(10, "Series2 G1", "Jan 04");
    dataSet.addValue(40, "Series2 G2", "Jan 04");

    dataSet.addValue(10, "Series3 G2", "Jan 04");
    dataSet.addValue(50, "Series3 G1", "Jan 04");

    dataSet.addValue(10, "Series4 G1", "Jan 04");
    dataSet.addValue(60, "Series4 G2", "Jan 04");

    // dataSet.addValue(100, "Series1 G1", "Jan 04");
    // dataSet.addValue(20, "Series1 G1", "Feb 04");
    // dataSet.addValue(10, "Series2 G1", "Jan 04");
    // dataSet.addValue(60, "Series2 G1", "Feb 04");
    // dataSet.addValue(99, "Series3 G1", "Feb 04");
    // dataSet.addValue(50, "Series3 G1", "Jan 04");
    // dataSet.addValue(100, "Series4 G1", "Feb 04");
    // dataSet.addValue(10, "Series4 G1", "Jan 04");
    //
    //
    // dataSet.addValue(150, "Series1 G2", "Jan 04");
    // dataSet.addValue(50, "Series1 G2", "Feb 04");
    // dataSet.addValue(40, "Series2 G2", "Jan 04");
    // dataSet.addValue(90, "Series2 G2", "Feb 04");
    // dataSet.addValue(10, "Series3 G2", "Jan 04");
    // dataSet.addValue(70, "Series3 G2", "Feb 04");
    // dataSet.addValue(60, "Series4 G2", "Jan 04");
    // dataSet.addValue(80, "Series4 G2", "Feb 04");

    return dataSet;
    }

    private static JFreeChart createChart(CategoryDataset categorydataset) {
    JFreeChart jfreechart = ChartFactory.createStackedBarChart("Sample", null, "value", categorydataset, PlotOrientation.VERTICAL, true, true, false);
    GroupedStackedBarRenderer renderer = new GroupedStackedBarRenderer();
    renderer.setItemMargin(0.01);
    renderer.setDrawBarOutline(false);

    renderer.setSeriesPaint(0, Color.blue);
    renderer.setSeriesPaint(1, Color.blue);

    renderer.setSeriesPaint(2, Color.cyan);
    renderer.setSeriesPaint(3, Color.cyan);

    renderer.setSeriesPaint(4, Color.green);
    renderer.setSeriesPaint(5, Color.green);

    renderer.setSeriesPaint(6, Color.yellow);
    renderer.setSeriesPaint(7, Color.yellow);

    // renderer.setSeriesPaint(0, Color.blue);
    // renderer.setSeriesPaint(4, Color.blue);
    //
    // renderer.setSeriesPaint(1, Color.cyan);
    // renderer.setSeriesPaint(5, Color.cyan);
    //
    // renderer.setSeriesPaint(2, Color.green);
    // renderer.setSeriesPaint(6, Color.green);
    //
    // renderer.setSeriesPaint(3, Color.yellow);
    // renderer.setSeriesPaint(7, Color.yellow);

    KeyToGroupMap keytogroupmap = new KeyToGroupMap("G1");
    keytogroupmap.mapKeyToGroup("Series1 G1", "G1");
    keytogroupmap.mapKeyToGroup("Series2 G1", "G1");
    keytogroupmap.mapKeyToGroup("Series3 G1", "G1");
    keytogroupmap.mapKeyToGroup("Series4 G1", "G1");

    keytogroupmap.mapKeyToGroup("Series1 G2", "G2");
    keytogroupmap.mapKeyToGroup("Series2 G2", "G2");
    keytogroupmap.mapKeyToGroup("Series3 G2", "G2");
    keytogroupmap.mapKeyToGroup("Series4 G2", "G2");

    renderer.setSeriesToGroupMap(keytogroupmap);
    SubCategoryAxis subcategoryaxis = new SubCategoryAxis("Series/Month");
    subcategoryaxis.setCategoryMargin(0.03);
    subcategoryaxis.addSubCategory("G1");
    subcategoryaxis.addSubCategory("G2");

    CategoryPlot categoryplot = (CategoryPlot) jfreechart.getPlot();
    categoryplot.setDomainAxis(subcategoryaxis);
    categoryplot.setRenderer(renderer);
    categoryplot.setFixedLegendItems(createLegendItems());

    return jfreechart;
    }

    private static LegendItemCollection createLegendItems() {
    LegendItemCollection legenditemcollection = new LegendItemCollection();
    LegendItem legenditem = new LegendItem("Series1", "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, Color.blue);
    LegendItem legenditem1 = new LegendItem("Series2", "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, Color.cyan);
    LegendItem legenditem2 = new LegendItem("Series3", "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, Color.green);
    LegendItem legenditem3 = new LegendItem("Series4", "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, Color.yellow);
    legenditemcollection.add(legenditem);
    legenditemcollection.add(legenditem1);
    legenditemcollection.add(legenditem2);
    legenditemcollection.add(legenditem3);
    return legenditemcollection;
    }

    public static void main(String args[]) {

    StackedBarChartTest demo = new StackedBarChartTest();

    ChartFrame frame = new ChartFrame("First", demo.createChart(demo.getData()));
    frame.pack();
    frame.setVisible(true);
    }
    }
    Note:
    • The SubCategoryAxis is used to assign labels to Category Axis' subcategories (i.e. groups).
    • The ChartFrame is used to display the results. The results could also be written to an output stream using the ChartUtilities.writeChartAsJPEG or ChartUtilities.writeChartAsPNG methods.
    • The commented lines show how the series color is affected by the order in which the data is entered into the Dataset.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...