public class DIYzhuzhuangtu {
public static void main(String[] args) {
String title = "柱状图测试";
String domain = "单位比较";
String range = "数值";
/**
* 初始化数据
*/
DefaultCategoryDataset data = new DefaultCategoryDataset();
for (int r = 0; r < 5; r++) {
String rowKey = "单位 [" + (r + 1)+"]" ;
for (int c = 0; c < 4; c++) {
String columnKey = "2006年" + (c + 1) + "月";
data.addValue(new Double(r * c + 3), rowKey, columnKey);
}
}
/**
* 建立JFreeChart对象
*/
JFreeChart chart=
ChartFactory.createBarChart(
title,
domain,
range,
data,
PlotOrientation.VERTICAL,
true,
true,
false);
/**
* 设置背景颜色和大小
*/
chart.setBackgroundPaint(
new GradientPaint(0, 0, Color.white, 1000, 0, Color.red));
chart.setTitle(new TextTitle(title, new Font("隶书", Font.ITALIC, 15)));
CategoryPlot plot = (CategoryPlot)chart.getPlot();
/**
* 设置字体
*/
plot.setForegroundAlpha(0.9f);
// plot.setValueLabelFont(new Font("黑体", Font.TRUETYPE_FONT, 12));
// plot.setSectionLabelFont(new Font("黑体", Font.TRUETYPE_FONT, 12));
// 注意以下代码
NumberAxis verticalAxis = (NumberAxis)plot.getRangeAxis();
verticalAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// 输出文件到指定目录
long time=new Date().getTime();
String rfname = "Pie_"+time+ ".jpeg";
String fileName = "d:\\" + rfname;
try {
ChartUtilities.saveChartAsJPEG(new File(fileName), 100, chart, 600, 600);
// log.info("....Create image File:" + fileName);
} catch (IOException exz) {
System.out.print("不能创建JPEG图片! 可能是文件的路径不正确");
}
System.out.println("输出保存在D://中 Pie_"+time+".jpeg");
}
}
本文介绍了一种使用Java实现柱状图的方法。通过初始化数据集并应用JFreeChart库,可以创建带有定制样式(如背景渐变色和中文标题)的柱状图,并将其保存为JPEG格式。
3202

被折叠的 条评论
为什么被折叠?



