【Java】JFreeChartを使って蜘蛛の巣チャートを作るサンプル。
説明
JFreeChartを利用して蜘蛛の巣チャートを作ってみます。
蜘蛛の巣チャートはレーダーチャートとも呼ばれていますね。
JFreeChartでは
SpiderWebPlotという名前で定義されています。
サンプル
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class ChartSample {
public static void main(String[] args) {
new ChartSample().createSpiderWebPlot();
}
public void createSpiderWebPlot() {
String name = "SampleSpiderWebPlotChart";
// 系列定義
String taro = "太郎";
String hanako = "花子";
// 項目定義
String category1 = "算数";
String category2 = "国語";
String category3 = "理科";
String category4 = "社会";
/***********************************************************************
* データセットを作成
**********************************************************************/
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
// 太郎
dataset.addValue(80, taro, category1);
dataset.addValue(20, taro, category2);
dataset.addValue(90, taro, category3);
dataset.addValue(75, taro, category4);
// 花子
dataset.addValue(70, hanako, category1);
dataset.addValue(90, hanako, category2);
dataset.addValue(70, hanako, category3);
dataset.addValue(95, hanako, category4);
/***********************************************************************
* チャートオブジェクトを作成
**********************************************************************/
// 蜘蛛の巣プロットを生成
SpiderWebPlot plot = new SpiderWebPlot(dataset);
// プロットに最大値を設定(100点満点)
plot.setMaxValue(100d);
// レーダーチャートの生成
JFreeChart chart = new JFreeChart("テスト結果", TextTitle.DEFAULT_FONT, plot,
true);
/***********************************************************************
* 出力
**********************************************************************/
// グラフの出力先
File outputFile = new File("./" + name + ".png");
try {
// ★★★ pngファイルで出力する場合
ChartUtilities.saveChartAsPNG(outputFile, chart, 400, 300);
// ★★★ 作成した画像をバイト配列で出力する場合
BufferedImage bufferedImage = chart.createBufferedImage(500, 500);
byte[] byteArray = ChartUtilities.encodeAsPNG(bufferedImage);
// ★★★ 作成した画像をInputStreamへ変換する場合
InputStream is = new ByteArrayInputStream(byteArray);
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
}
参考
JFreeChartのチラシノウラ
http://goodjob.boy.jp/chirashinoura/search/JFreeChart.html