Creating Time Series Chart With JFree Chart

In this basic tutorial, I will teach you how to create a simple timeseries chart in Java using the free JFreeChart. The program uses the following two jar files, and they come with the JFreeChart itself. You can download JFreeChart at their official website www.jfreechart.org

  • jcommon-1.0.15.jar
  • jfreechart-1.0.12.jar

The program also demonstrates how easily you can save a generated chart to your computer using the Charts Utilities from JFreeChart

package com.kushal.utilities;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

public class TimeSeriesChartDemo {

	public void createTimeSeriesXYChart()
	{

		TimeSeries series = new TimeSeries( "", Day.class );

		series.add(new Day(new Date("2009/01/01")), 123);
		series.add(new Day(new Date("2009/01/02")), 133);
		series.add(new Day(new Date("2009/01/03")), 99);
		series.add(new Day(new Date("2009/01/04")), 113);
		series.add(new Day(new Date("2009/01/05")), 159);
		series.add(new Day(new Date("2009/01/06")), 124);
		series.add(new Day(new Date("2009/01/07")), 120);

        TimeSeriesCollection dataset=new TimeSeriesCollection();
        dataset.addSeries(series);

        JFreeChart chart = ChartFactory.createTimeSeriesChart
        ("User Participation Chart", 	// Title
         "Day",              		// X-Axis label
         "Number Of Users",             // Y-Axis label
         dataset,         		// Dataset
         true,                     	// Show legend
         true,				//tooltips
         false				//url
        );

        saveChart(chart);

	}

	public void saveChart(JFreeChart chart)
	{
		String fileName="C:/Users/kushal/Desktop/myTimeSeriesChart.jpg";
		try {
			/**
			 * This utility saves the JFreeChart as a JPEG
			 * First Parameter: FileName
			 * Second Parameter: Chart To Save
			 * Third Parameter: Height Of Picture
			 * Fourth Parameter: Width Of Picture
			 */
            ChartUtilities.saveChartAsJPEG(new File(fileName), chart, 800, 600);
        } catch (IOException e) {
        	e.printStackTrace();
            System.err.println("Problem occurred creating chart.");
        }
	}
	public static void main(String args [])
	{
		new TimeSeriesChartDemo().createTimeSeriesXYChart();

	}

}


The following is the output of this program

Displaying A List Of All Available Fonts Using Java

Most of the tutorials I write in my blogs are because one way or the other I need these programs for myself. I recently ran into a similar situation. I was working on one of application where I was trying to resize an image and put a water mark on top of this image. (This will be my upcoming tutorial). Then I needed a good looking font. I knew there are lots of Fonts installed on my machine, and I can get a preview of them when I use Adobe Photoshop. But I had no idea what would their names be to be used in my application. So I did a little research and wrote this program that list all available fonts from the local system.

First I found the method from ToolKit class. I wrote a simple class to use that method. To my wonder, it just printed 5 fonts. Definitely I didn’t have just five fonts in my machine. The method I used Toolkit.getDefaultToolkit().getFontList(), which I later discovered was a depricated method and only provided me a few primitive fonts.

So, another small research led me to GraphicsEnvironment.getAvailableFontFamilyNames() method which was what I exactly wanted. It listed the names of all the fonts that are available in my machine.

I am presenting you here a class that uses both the methods mentioned above to find a list of available fonts.

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 05-21-2009
 */
package com.kushal.utils;

import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;

/**
 * Demonstrating  How To Get the
 * Available Font Names Using Java
 *
 */
public class AvailableFontLister {

	public static void main(String args [])
	{
		System.out.println("***************************");
		System.out.println("**Listing Fonts Using Deprecated Method From ToolKit Class**");
		listUsingToolKit();
		System.out.println();

		System.out.println("****************************");
		System.out.println("**Listing Fonts Using Method From GraphicsEnvironment Class**");
		listUsingGraphicsEnvironment ();

	}

	/**
	 * Prints a list of all available fonts from
	 * the local graphics environment.
	 *
	 * The output list varies from manchine to machine
	 */
	public static void listUsingGraphicsEnvironment ()
	{
		GraphicsEnvironment ge= null;

		ge=GraphicsEnvironment.getLocalGraphicsEnvironment();

		String []fontNames=ge.getAvailableFontFamilyNames();

		for (int i = 0; i< fontnames.length; i++) {
			System.out.println(fontnames[i]);
		}
	}

}

———————————–
Sample Output Of This Program On My Machine

***************************
**Listing Fonts Using Deprecated Method From ToolKit Class**
Dialog
SansSerif
Serif
Monospaced
DialogInput
<!--more-->
****************************
**Listing Fonts Using Method From GraphicsEnvironment Class**
Agency FB
Algerian
Arial
Arial Black
Arial Narrow
Arial Rounded MT Bold
Arial Unicode MS
Baskerville Old Face
Bauhaus 93
Bell MT
Berlin Sans FB
Berlin Sans FB Demi
Bernard MT Condensed
Blackadder ITC
Bodoni MT
Bodoni MT Black
Bodoni MT Condensed
Bodoni MT Poster Compressed
Book Antiqua
Bookman Old Style
Bookshelf Symbol 7
Bradley Hand ITC
Britannic Bold
Broadway
Brush Script MT
Calibri
Californian FB
Calisto MT
Cambria
Cambria Math
Candara
Castellar
Centaur
Century
Century Gothic
Century Schoolbook
Chiller
Colonna MT
Comic Sans MS
Consolas
Constantia
Cooper Black
Copperplate Gothic Bold
Copperplate Gothic Light
Corbel
Courier New
CourierThai
Curlz MT
Devanagari MT for IBM
Dialog
DialogInput
Edwardian Script ITC
Elephant
Engravers MT
Eras Bold ITC
Eras Demi ITC
Eras Light ITC
Eras Medium ITC
Estrangelo Edessa
Felix Titling
Footlight MT Light
Forte
Franklin Gothic Book
Franklin Gothic Demi
Franklin Gothic Demi Cond
Franklin Gothic Heavy
Franklin Gothic Medium
Franklin Gothic Medium Cond
Freestyle Script
French Script MT
Garamond
Gautami
Georgia
Gigi
Gill Sans MT
Gill Sans MT Condensed
Gill Sans MT Ext Condensed Bold
Gill Sans Ultra Bold
Gill Sans Ultra Bold Condensed
Gloucester MT Extra Condensed
Goudy Old Style
Goudy Stout
Haettenschweiler
Harlow Solid Italic
Harrington
High Tower Text
Impact
Imprint MT Shadow
Informal Roman
Jokerman
Juice ITC
Kristen ITC
Kunstler Script
Latha
Lucida Bright
Lucida Calligraphy
Lucida Console
Lucida Fax
Lucida Handwriting
Lucida Sans
Lucida Sans Typewriter
Lucida Sans Unicode
Magneto
Maiandra GD
Mangal
Marlett
Matura MT Script Capitals
Microsoft Sans Serif
Mistral
Modern No. 20
Monospaced
Monotype Corsiva
MS Mincho
MS Outlook
MS Reference Sans Serif
MS Reference Specialty
MT Extra
MV Boli
Niagara Engraved
Niagara Solid
OCR A Extended
Old English Text MT
Onyx
Palace Script MT
Palatino Linotype
Papyrus
Parchment
Perpetua
Perpetua Titling MT
Playbill
Poor Richard
Pristina
Raavi
Rage Italic
Ravie
Rockwell
Rockwell Condensed
Rockwell Extra Bold
SansSerif
Script MT Bold
Segoe UI
Serif
Showcard Gothic
Shruti
Snap ITC
Stencil
Sylfaen
Symbol
Tahoma
Tempus Sans ITC
Thonburi
Times New Roman
Trebuchet MS
Tunga
Tw Cen MT
Tw Cen MT Condensed
Tw Cen MT Condensed Extra Bold
Verdana
Viner Hand ITC
Vivaldi
Vladimir Script
Webdings
Wide Latin
Wingdings
Wingdings 2
Wingdings 3

P.S. This article was previously published in my another blog at Sanjaal.com

Creating A 3D Category Bar Chart In Java Using JFreeChart [Example Source Code]

About Bar Chart:
A bar chart or bar graph is a chart with rectangular bars with lengths proportional to the values that they represent. Bar charts are used for comparing two or more values that were taken over time or on different conditions, usually on small data sets. The bars can be horizontally oriented (also called bar chart) or vertically oriented (also called column chart). Sometimes a stretched graphic is used instead of a solid bar. It is a visual display used to compare the amount or frequency of occurrence of different characteristics of data and it is used to compare groups of data.

About JFreeChart:
JFreeChart is an open-source framework for the programming language Java, which allows the creation of complex charts in a simple way.

JFreeChart also works with GNU Classpath, a free software implementation of the standard class library for the Java programming language.

Following chart types are supported:

  • X-Y charts (line, spline and scatter)
  • Pie charts
  • Gantt charts
  • Bar charts (horizontal and vertical, stacked and independent)
  • Single valued (thermometer, compass, speedometer)

If you do not have the JFreeChart library and API, you can download it from their website www.jfree.org

My Tutorial / Example Source Code:
My Tutorial focuses on creating a category bar chart. In this tutorial we will

  • — Create Sample Category Data Set
  • — Create a 3D Category Bar Chart with the sample data. This graph will have horizontal plot orientation.
  • — We will then save the generated chart to the filesystem.
  • — We will repeat to create a plot with vertical orientation and also save the generated vertically oriented bar chart to the filesystem.

The program code, sample output, and the generated charts are given below.

package com.kushal.charts;
/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modfied On: 2009-09-23
 *
 * Using JFreeChart to create 3D Category Bar Chart
 */
import java.awt.Color;
import java.io.File;
import java.io.IOException;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

public class My3DCategoryChart {
private static final long serialVersionUID = -8625975218180144099L;

private CategoryDataset createCategoryDataset() {
final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(225.0, "15-20 Years", "Male");
dataset.addValue(419.0, "20-30 Years", "Male");
dataset.addValue(141.0, "30-40 Years", "Male");

dataset.addValue(634.0, "15-20 Years", "Female");
dataset.addValue(229.0, "20-30 Years", "Female");
dataset.addValue(433.0, "30-40 Years", "Female");
return dataset;

}

private JFreeChart create3DBarChart(CategoryDataset dataset,
PlotOrientation plotOrientation) {
JFreeChart chart = ChartFactory.createBarChart3D(
"3D Bar Chart Demo - www.sanjaal.com/java", //Chart Title
"Gender", //Domain Axis Label
"Avg Minutes Spent On Sanjaal.com Per Day", //Range Axis Label
dataset, //Data
plotOrientation, //Orientation
true, //Include Legend
true, //Tooltips
false //Urls
);

CategoryPlot plot = chart.getCategoryPlot();
CategoryAxis axis = plot.getDomainAxis();
axis.setCategoryLabelPositions(CategoryLabelPositions
.createUpRotationLabelPositions(Math.PI / 16.0));

CategoryItemRenderer renderer = plot.getRenderer();
BarRenderer r = (BarRenderer) renderer;
r.setMaximumBarWidth(0.1);
chart.setBackgroundPaint(Color.WHITE);

return chart;

}

public void saveChart(JFreeChart chart, String fileLocation) {
try {
/**
* This utility saves the JFreeChart as a JPEG First Parameter:
* FileName Second Parameter: Chart To Save Third Parameter: Height
* Of Picture Fourth Parameter: Width Of Picture
*/
ChartUtilities.saveChartAsJPEG(new File(fileLocation), chart, 800,
600);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Problem occurred creating chart.");
}
}

public static void main(String[] args) {
My3DCategoryChart chartCreator = new My3DCategoryChart();

/** Create a Category Data Set* */
CategoryDataset categoryDataset = chartCreator.createCategoryDataset();

/** Create 3D Category Chart (Horizontal) based on this dataset* */
JFreeChart chartHorizontal = chartCreator.create3DBarChart(
categoryDataset, PlotOrientation.HORIZONTAL);

/** Define a location to save this created file* */
String horizontalChartFileSaveLocation = "C:/temp/my3DCategoryChartHorizontal.jpg";

/** Save the chart to the file system* */
chartCreator
.saveChart(chartHorizontal, horizontalChartFileSaveLocation);
System.out.println("Horizontal Category Chart Created Successfully");
System.out.println("Chart has been saved to: "
+ horizontalChartFileSaveLocation);

/** Create 3D Category Chart (Vertical) based on this dataset* */
JFreeChart chartVertical = chartCreator.create3DBarChart(
categoryDataset, PlotOrientation.VERTICAL);

/** Define a location to save this created file* */
String verticalChartFileSaveLocation = "C:/temp/my3DCategoryChartVertical.jpg";

/** Save the chart to the file system* */
chartCreator.saveChart(chartVertical, verticalChartFileSaveLocation);

System.out.println("nVertical Category Chart Created Successfully");
System.out.println("Chart has been saved to: "
+ verticalChartFileSaveLocation);

}

/*
* SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
* PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
* NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
* SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
* SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
* PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
* HIGH RISK ACTIVITIES.
*/
}

The following is the output of this program.

Horizontal Category Chart Created Successfully
Chart has been saved to: C:/temp/my3DCategoryChartHorizontal.jpg

Vertical Category Chart Created Successfully
Chart has been saved to: C:/temp/my3DCategoryChartVertical.jpg

The chart that are generated by this application are given below.

Horizontally Oriented Category Bar Chart:

Vertically Oriented Category Bar Chart: