Reader small image

You're reading from  PrimeFaces Beginner's Guide

Product typeBook
Published inNov 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781783280698
Edition1st Edition
Languages
Right arrow
Author (1)
Siva Prasad Reddy Katamreddy
Siva Prasad Reddy Katamreddy
author image
Siva Prasad Reddy Katamreddy

K. Siva Prasad Reddy is a Senior Software Engineer living in Hyderabad, India, and having more than seven years of experience in developing enterprise applications with Java and JavaEE technologies. Siva is a Sun Certified Java Programmer and has a lot of experience in server-side technologies such as Java, JavaEE, Spring, Hibernate, MyBatis, JSF, PrimeFaces, and WebServices (SOAP/REST). Siva is also the author of Java Persistence with MyBatis 3, Packt Publishing. Siva normally shares the knowledge he has acquired on his blog at www.sivalabs.in. If you want to find out more about his work, you can follow him on Twitter (@sivalabs) and GitHub (https://github.com/sivaprasadreddy).
Read more about Siva Prasad Reddy Katamreddy

Right arrow

Chapter 12. Drawing Charts

Businesses use various reporting tools to compare results and measure performance. Often businesses want reports in graphical representations such as charts so that it will be easy to compare the results and measure the overall performance of their business. PrimeFaces provides support for creating various types of charts, such as Line, Area, Bar, Pie, Donut, Bubble, MeterGauge, and Open High Low Close (OHLC). PrimeFaces also supports rendering charts generated by JFreeCharts.

In our TechBuzz application, administrators can see the statistics of the number of posts by tags, in each year, with graphical representation using various types of charts.

In this chapter, we will cover the following commonly used charts:

  • Creating a Line chart

  • Creating an Area chart

  • Creating a Bar chart

  • Creating a Pie chart

  • Creating a Donut chart

  • Exporting charts as images

  • Rendering dynamic charts using the JFreeChart API

  • Creating interactive charts using the ItemSelect AJAX event

Creating a Line chart


A Line chart represents a series of data points in a line graph. The Line chart data model should be an instance of org.primefaces.model.chart.CartesianChartModel.

Let us see how to visualize a number of posts for various tags in each year using the Line chart.

<p:lineChart value="#{chartController.chartModel}" legendPosition="se"/>

The chartModel can be created and initialized as follows:

public ChartController()
{
  CartesianChartModel chartModel = new CartesianChartModel();
  
  ChartSeries primefacesSeries = new ChartSeries();
  primefacesSeries.setLabel("PrimeFaces");
  primefacesSeries.set("2009", 150);
  primefacesSeries.set("2010", 250);
  primefacesSeries.set("2011", 300);
  primefacesSeries.set("2012", 240);
  primefacesSeries.set("2013", 400);

  ChartSeries jquerySeries = new ChartSeries();
  querySeries.setLabel("jQuery");
  jquerySeries.set("2009", 210);
  jquerySeries.set("2010", 150);
  jquerySeries.set("2011", 200);
  jquerySeries.set("2012", 280...

Time for action – creating a Line chart


In this section, we will create a Line chart depicting the number of posts with PrimeFaces and jQuery tags from years 2009 to 2013.

  1. Create a Line chart with custom labels, axis angles, series colors, and enable zooming and animation.

    <p:lineChart value="#{chartController.chartModel}" 
      style="width: 450px; height: 300px;"
      title="Linear Chart" 
      legendPosition="nw" 
      xaxisLabel="Year" yaxisLabel="No. of Posts" 
      xaxisAngle="45" yaxisAngle="45"
      minY="0" maxY="1000"
      breakOnNull="true" zoom="true" animate="true"
      seriesColors="800000,006400"
      legendCols="2"/>

What just happened?

Here, we have specified the labels and angles for X-axis and Y-axis. We have also customized the series to display #800000 and #006400 colors instead of the default colors. As we have specified breakOnNull="true" the jQuery series disconnected at year 2011. If you set breakOnNull="false", which is the default, the jQuery data point at year 2010 will be directly connected...

Creating an Area chart


We can create an Area chart using the Line chart component by setting fill="true" to fill under the lines from the X-axis, which visually looks like an Area chart. Also, we can set stacked="true" to display the series stacked on top of the other series by adding data sets.

Let us see how we can create Area charts using the <p:lineChart> component by using fill and stacked attributes.

<p:lineChart title="Area Chart" value="#{chartController.chartModel}" 
  legendPosition="nw" style="width: 450px; height: 300px;"
  xaxisLabel="Year" yaxisLabel="No. of Posts" xaxisAngle="45" yaxisAngle="45"
  minY="0" maxY="1000"
  fill="true" stacked="true"/>

Here we have created a Stacked Area chart using the <p:lineChart> component by setting fill="true" and stacked="true".

Creating a Bar chart


The Bar chart component visualizes a series of data points as bars. We can use the same org.primefaces.model.chart.CartesianChartModel type instance, which we used for the Line chart, to provide the data for the Bar chart.

Let us create a Bar chart representing tags usage statistics over recent years.

<p:barChart value="#{chartController.chartModel}" legendPosition="nw" style="width: 400px; height: 250px;" />

A Bar chart also supports most of the features supported by the Line chart, such as labels and angles for X and Y axis, various legendPositions, seriesColors, stacked, zoom, animate, custom dataTipFormat, and so on. In addition to these options, the Bar chart provides the following options to customize its behavior:

  • barPadding: This is the padding of the bars. The default value for it is 8.

  • barMargin: This is the margin of the bars. The default value for it is 10.

  • orientation: This is the orientation of the bars, the valid values for it are vertical and horizontal...

Time for action – creating a Bar chart


Let us look at creating a Bar chart with horizontal orientation displaying the number of posts with PrimeFaces and jQuery tags from years 2009 to 2013.

  1. Create a Bar chart using horizontal orientation with custom seriesColors and dataTipFormat.

    <p:barChart value="#{chartController.chartModel}" 
      style="width: 400px; height: 250px;"
      xaxisLabel="No. of Posts" yaxisLabel="Year" 
      xaxisAngle="45" 
      datatipFormat="#{chartController.datatipFormat}"
      legendPosition="se" barMargin="5" barPadding="4" 
      seriesColors="A52A2A, 1E90FF"
      orientation="horizontal" animate="true" 
      />
  2. Write a method to return the custom dataTipFormat.

    public String getDatatipFormat() 
    {
      return "<span>No. of Posts: %s</span>";
    }

What just happened?

We have created a horizontal Bar chart by setting orientation="horizontal". We have customized the series colors by setting seriesColors="A52A2A, 1E90FF".

Also we have customized the datatip format using the datatipFormat...

Creating a Pie chart


The Pie chart component renders the category data as a Pie chart. The Pie chart uses the org.primefaces.model.chart.PieChartModel type instance as a backing bean model.

Let us see how we can create a Pie chart representing the percentage of posts being created with various tags:

<p:pieChart value="#{chartController.pieChartModel}"
  style="width: 350px; height: 250px;"
  showDataLabels="true" legendPosition="ne"/>

public class ChartController
{
  private PieChartModel pieChartModel;
  public ChartController()
  {
    pieChartModel = new PieChartModel();
    pieChartModel.set("JSF", 380);
    pieChartModel.set("PrimeFaces", 455);
    pieChartModel.set("jQuery", 202);
    pieChartModel.set("JPA", 180);
  }
  public PieChartModel getPieChartModel()
  {
    return pieChartModel;
  }
}

The preceding code renders a Pie chart as follows:

In addition to the title, legendPosition, seriesColors, fill, shadow, legendCols, legendRows, extender options, the Pie chart component...

Time for action – creating a Pie chart


In this section we are going to create a Pie chart with various customization options, such as diameter, sliceMargin, and dataFormat showing the total number of posts that are posted with each tag.

  1. Create a Pie chart without filling the slices with colors, gaps between slices, and displaying the slice data value instead of the percentage.

    <p:pieChart value="#{chartController.pieChartModel}"
      style="width: 350px; height: 250px;"
      title="Post Statistics By Tag"legendPosition="ne" 
      legendCols="2"
      showDataLabels="true"
      diameter="150"
      sliceMargin="5"
      fill="false"
      dataFormat="value"/>

What just happened?

We have created a Pie chart by disabling the color filling for slices by setting fill= "false". By setting the dataFormat= "value", the slice data value will be displayed instead of the percentage. Also we have specified the custom diameter value instead of using the computed value.

Creating a Donut chart


The Donut chart visualizes a multiseries Pie chart in a single plot. The Donut chart uses the org.primefaces.model.chart.DonutChartModel type instance as a backing bean model.

Let us see how we can create a Donut chart representing the number of posts being posted with various tags in years 2011, 2012, and 2013 years.

<p:donutChart value="#{chartController.donutChartModel}" 
  style="width: 350px; height: 250px;"
  legendPosition="se"
  sliceMargin="5" 
  dataFormat="value" />

public class ChartController
{
  private DonutChartModel donutChartModel;
  public ChartController()
  {
    donutChartModel = new DonutChartModel();
    Map<String, Number> year2011Circle = new HashMap<String, Number>();
    year2011Circle.put("PrimeFaces", 80);
    year2011Circle.put("jQuery", 350);
    year2011Circle.put("JSF", 50);
    donutChartModel.addCircle(year2011Circle);
    
    Map<String, Number> year2012Circle = new HashMap<String, Number>();
    year2012Circle...

Exporting charts as images


PrimeFaces provides the ability to export charts generated by various chart components as images using the client-side API method widgetVar.exportAsImage().

<h:form id="form1">
  <p:lineChart widgetVar="chartWgt" 
    value="#{chartController.chartModel}" 
      style="width:500px;height:300px" 
      title="Linear Chart" 
      legendPosition="e"
      minY="0" maxY="600"/>
  
  <p:commandButton type="button" value="Export" onclick="exportChart()"/>

  <p:dialog widgetVar="dlg" showEffect="fade" modal="true" header="Chart as an Image">
    <p:outputPanel id="output" layout="block" style="width:500px;height:300px"/>
  </p:dialog> 
 </h:form>
<script type="text/javascript">
  function exportChart() 
  {
    $(PrimeFaces.escapeClientId('form1:output')).empty().append(chartWgt.exportAsImage());
    dlg.show();
  }
</script>

Here, we have created a Line chart with widgetVar= "chartWgt". When you click on the Export...

Rendering dynamic charts using the JFreeChart API


PrimeFaces internally uses the jqPlot library, which is based on jQuery, to generate charts using a canvas element. We can also create charts on the server side using the JFreeChart library (http://www.jfree.org/jfreechart/) and render the chart images using the PrimeFaces <p:graphicImage> component.

To add the JFreeChart jar file to the classpath, add the following maven dependency.

<dependency>
  <groupId>jfree</groupId>
  <artifactId>jfreechart</artifactId>
  <version>1.0.13</version>
</dependency>

Let us see how we can create a Pie chart using the JFreeChart API and render it using the PrimeFaces <p:graphicImage>.

Time for action – creating a Pie chart using the JFreeChart API


In this section, we will demonstrate how to create a Pie chart using the JFreeChart API and rendering it using the <p:graphicImage> and StreamedContent API.

  1. Create a Pie chart using the JFreeChart API and attach the PrimeFaces StreamedContent to a stream-generated chart image.

    import java.io.File;
    import java.io.FileInputStream;
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartUtilities;
    import org.jfree.chart.JFreeChart;
    import org.jfree.data.general.DefaultPieDataset;
    import org.jfree.data.general.PieDataset;
    import org.primefaces.model.DefaultStreamedContent;
    import org.primefaces.model.StreamedContent;
    public StreamedContent getJfreeChart()
    {
      StreamedContent content = null;
      try
      {
        DefaultPieDataset dataset = new DefaultPieDataset();  
        dataset.setValue("PrimeFaces", 455);
        dataset.setValue("JSF", 380);
        dataset.setValue("jQuery", 202);
        dataset.setValue("JPA", 180);
        
        boolean...

Creating interactive charts using the ItemSelect AJAX event


All of the PrimeFaces chart components support the itemSelect AJAX event which gets triggered when a series of charts are clicked on. The itemSelect event listener method receives an org.primefaces.event.ItemSelectEvent instance from which we can obtain an item index and a series index.

<p:growl id="growl" showDetail="true"/>

<p:pieChart value="#{chartController.pieChartModel}"
  style="width: 350px; height: 250px;"
  showDataLabels="true" legendPosition="ne">
  <p:ajax event="itemSelect" listener="#{chartController.itemSelect}" update="growl"/>
</p:pieChart>

public void itemSelect(ItemSelectEvent event) 
{  
  FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Item selected",  "Item Index: " + event.getItemIndex() + ", Series Index:" + event.getSeriesIndex()); 
  FacesContext.getCurrentInstance().addMessage(null, msg);  
}

We can use this itemSelect event listener to build drilldown charts...

Summary


In this chapter, we have learned how to create various types of charts, such as Line, Area, Bar, and Donut. We also looked at exporting charts as images using the client-side API. In addition, we have looked into how to create dynamic images on the server side using the JFreeChart library and displaying them as a graphic image.

In the next chapter, we will look into how to use various built-in PrimeFaces themes, and how to build applications supporting multiple themes with the ability to switch themes dynamically.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
PrimeFaces Beginner's Guide
Published in: Nov 2013Publisher: PacktISBN-13: 9781783280698
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Siva Prasad Reddy Katamreddy

K. Siva Prasad Reddy is a Senior Software Engineer living in Hyderabad, India, and having more than seven years of experience in developing enterprise applications with Java and JavaEE technologies. Siva is a Sun Certified Java Programmer and has a lot of experience in server-side technologies such as Java, JavaEE, Spring, Hibernate, MyBatis, JSF, PrimeFaces, and WebServices (SOAP/REST). Siva is also the author of Java Persistence with MyBatis 3, Packt Publishing. Siva normally shares the knowledge he has acquired on his blog at www.sivalabs.in. If you want to find out more about his work, you can follow him on Twitter (@sivalabs) and GitHub (https://github.com/sivaprasadreddy).
Read more about Siva Prasad Reddy Katamreddy