Live Data on Charts

Last week, I’ve written about the flash based chart components of PrimeFaces. Another nice feature I didn’t mention yet is that, charts are capable of displaying live data based on polling. As an example, suppose there’s an ongoing vote between two candidates and a pie chart displays the current status of the vote.


Check out the Online Demo of Live Data on Charts

If you’re wondering about how it works, check out the link above to see the online demo.

The implementation is simple, just like a regular chart, you need to model the chart data, since there’s a vote going on, you can use a Vote class to represent this.

public class Vote {

	private String candidate;

	private int count;

	public Vote() {

	public Vote(String candidate, int count) {
		this.candidate = candidate;
		this.count = count;

	public String getCandidate() {
		return candidate;

	public void setCandidate(String candidate) {
		this.candidate = candidate;

	public int getCount() {
		return count;

	public void setCount(int count) {
		this.count = count;

	public void add(int count) {
		this.count = this.count + count;

And the ChartBean to provide the vote data;

import java.util.ArrayList;
import java.util.List;

import org.primefaces.examples.domain.Birth;
import org.primefaces.examples.domain.Vote;
import org.primefaces.optimus.config.Scope;
import org.primefaces.optimus.config.annotations.Controller;

@Controller(name="chartBean", scope=Scope.VIEW)
public class ChartBean implements Serializable {

	private List<Vote> votes;

	public ChartBean() {
		votes = new ArrayList<Vote>();
		votes.add(new Vote("Candidate 1", 100));
		votes.add(new Vote("Candidate 2", 100));

	public List<Vote> getVotes() {
		int random1 = (int)(Math.random() * 1000);
		int random2 = (int)(Math.random() * 1000);


		return votes;

Note that for dummy data, int getVotes() random number of votes are added to the candidate votes, probably in a real application you may use a webservice or a similar stuff to fetch the live data.(like stock market)

Finally, the pie chart on the page;

<p:pieChart id="votes" value="#{chartBean.votes}" var="vote"
					live="true" refreshInterval="5000"
					categoryField="#{vote.candidate}" dataField="#{vote.count}" />

To make chart live, only one attribute is needed, live=”true”. With this setting chart calls getVotes() in a 3 seconds polling interval and then returns the new data in json format, finally chart updates itself with the json data. Polling interval is tuned using the refreshInterval attribute.

All chart components bar, column, line, etc of PrimeFaces supports live data display. Also note that this feature is added after 0.8.0 release.

One Response to Live Data on Charts

  1. Pingback: Interactive JSF Charts « Cagatay Civici’s Weblog

%d bloggers like this: