jfreechart折线图 demo

public class ChartUtil {

public static ChartUtil chartUtil;
private RoomViewsDataService roomViewsDataService;
/**
* 创建报表图
* @return
* @throws IOException
*/
public static String createChartImage(String userId ,String userName , String livingId) throws IOException{
//生成3D折线图(柱状图只改方法名createLineChart3D就可以了)
JFreeChart chart = ChartFactory.createLineChart (
userName + "直播统计图", //图表标题
"时间(分钟)", //目录轴的显示标签
"人数", //数值轴的显示标签
getDataSet(livingId), //数据
//PlotOrientation.HORIZONTAL, //图表方向水平
PlotOrientation.VERTICAL, //图表方向垂直
true, //是否显示图例
true, //是否显示工具提示
true //是否生成URL
);
//设置标题及标题字体
chart.setTitle(new TextTitle(userName + "直播统计图",new Font("黑体",Font.ITALIC,22)));
//建一个图例
LegendTitle legendTitle = chart.getLegend(0);
//设置图例字体
legendTitle.setItemFont(new Font("宋体",Font.BOLD,14));
//获取折线图plot对象
CategoryPlot plot = (CategoryPlot) chart.getPlot();
//设置折线的颜色
plot.getRenderer().setSeriesPaint(0, Color.RED);
// plot.getRenderer().setSeriesPaint(1, Color.GREEN);
// plot.getRenderer().setSeriesPaint(2, Color.ORANGE);
//取得横轴
CategoryAxis categoryAxis = plot.getDomainAxis();
//设置横轴的字体
categoryAxis.setLabelFont(new Font("宋体",Font.BOLD,12));
//设置分类标签以45度倾斜
//categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
//设置分类标签字体
categoryAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12));
//取得纵轴
NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
//Y轴显示整数
numberAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
//设置纵轴的字体
numberAxis.setLabelFont(new Font("宋体",Font.BOLD,12));
//设置背景透明度(0~1)
plot.setBackgroundAlpha(0.9f);
//设置前景色透明度(0~1)
plot.setForegroundAlpha(0.5f);
//输出文件
String filePath = CreateDelFileUtils.delAndCreateSessionUser(userId ,userName) + "/" + userId + ".jpg";
System.out.println(filePath);
FileOutputStream fos = new FileOutputStream(filePath);
//用ChartUtilities工具输出
ChartUtilities.writeChartAsJPEG(fos, chart, 650, 350);
fos.close();
return filePath;
}
/**
* 设置数据集
* @return
*/
private static CategoryDataset getDataSet(String livingId) {
//提供生成折线图的数据
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
//生成复杂带图例的柱状图
List<RoomViewsDataModel> rvdms = chartUtil.roomViewsDataService.getDataByLivinId(livingId);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
for(int i = 0 , n = rvdms.size() ; i < n; i++){

dataset.addValue(rvdms.get(i).getViews(), "人数", sdf.format(rvdms.get(i).getDate()));
}
return dataset;
}
public RoomViewsDataService getRoomViewsDataService() {
return roomViewsDataService;
}
public void setRoomViewsDataService(RoomViewsDataService roomViewsDataService) {
this.roomViewsDataService = roomViewsDataService;
}
public void init(){
chartUtil = this;
chartUtil.roomViewsDataService = roomViewsDataService;
}
}

原文地址:https://www.cnblogs.com/lovezhaolei/p/3251037.html