JFreechart Stacked Bar Chart


 

JFreechart Stacked Bar Chart

JFreechart provides a way to create various charts by just using the methods of different classes. Here we are going to create a Stacked Bar Chart.

JFreechart provides a way to create various charts by just using the methods of different classes. Here we are going to create a Stacked Bar Chart.

JFreechart Stacked Bar Chart

JFreechart provides a way to create various charts by just using the methods of different classes. You are well aware of bar chart, pie chart, line chart,area chart etc. Here we are going to create a Stacked Bar Chart. This chart actually displays the result of multiple queries stacks on top of one another which is an effective way to communicate the absolute values of data points represented by  the segments of each bar, as well as the total value represented by data points from each series stacked in a bar.

In the following example, each bar of the stacked bar graph is divided into two categories: girls and boys and display their interest regarding games. For example, 25 students like Chess, out of which 10 are girls and 15 are boys.

Here is the code:

import org.jfree.ui.*;
import org.jfree.chart.*;
import org.jfree.data.category.*;
import org.jfree.chart.plot.PlotOrientation;

public class StackedBarChart extends ApplicationFrame {
	public StackedBarChart(final String title) {
		super(title);
		final CategoryDataset dataset = createDataset();
		final JFreeChart chart = createChart(dataset);
		final ChartPanel chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
		setContentPane(chartPanel);
	}

	private CategoryDataset createDataset() {
		DefaultCategoryDataset result = new DefaultCategoryDataset();

		result.addValue(10, "Girls", "Chess");
		result.addValue(15, "Boys", "Chess");
		result.addValue(17, "Girls", "Cricket");
		result.addValue(23, "Boys", "Cricket");
		result.addValue(25, "Girls", "FootBall");
		result.addValue(20, "Boys", "FootBall");
		result.addValue(40, "Girls", "Badminton");
		result.addValue(30, "Boys", "Badminton");
		result.addValue(35, "Girls", "Hockey");
		result.addValue(32, "Boys", "Hockey");
		return result;
	}

	private JFreeChart createChart(final CategoryDataset dataset) {
		final JFreeChart chart = ChartFactory.createStackedBarChart(
				"Stacked Bar Chart", "Games", "No. of students", dataset,
				PlotOrientation.VERTICAL, true, true, false);
		return chart;
	}

	public static void main(final String[] args) {
		final StackedBarChart demo = new StackedBarChart("Stacked Bar Chart");
		demo.pack();
		RefineryUtilities.centerFrameOnScreen(demo);
		demo.setVisible(true);
	}
}

Output:

Ads