使用JFreeChart在网页上绘制平滑曲线

来源:互联网 发布:设计协作软件 编辑:程序博客网 时间:2024/04/29 22:14

在做一个与细胞仿真有关的小软件时遇到了这个需求,最后选择了JFreeChart类库
百度百科关于JFreeChart的简介

用JFreeChart可以很轻松地画出很多种类常用的图形,如饼图、柱状图、折线图等,而绘制平滑曲线的功能是从版本1.0.7开始才增加的。

绘制平滑曲线的核心代码如下:

XYSplineRenderer renderer = new XYSplineRenderer();renderer.setBaseShapesVisible(false); //绘制的线条上不显示图例,如果显示的话,会使图片变得很丑陋renderer.setSeriesPaint(0, Color.GREEN); //设置0号数据的颜色。这是手工设置线条颜色的方法renderer.setPrecision(5); //设置精度,大概意思是在源数据两个点之间插入5个点以拟合出一条平滑曲线 //create plotNumberAxis xAxis = new NumberAxis("Time(ns)");xAxis.setAutoRangeIncludesZero(false);NumberAxis yAxis = new NumberAxis("Voltage(mv)");yAxis.setAutoRangeIncludesZero(false); XYPlot plot = new XYPlot(createDataset("D:/V.dat"), xAxis, yAxis, renderer);plot.setBackgroundPaint(Color.black);plot.setDomainGridlinePaint(Color.white);plot.setRangeGridlinePaint(Color.white);plot.setAxisOffset(new RectangleInsets(4, 4, 4, 4)); //设置坐标轴与绘图区域的距离 JFreeChart chart = new JFreeChart("细胞电压图", //标题JFreeChart.DEFAULT_TITLE_FONT, //标题的字体,这样就可以解决中文乱码的问题plot,false //不在图片底部显示图例); //设置X轴的显示格式XYPlot   xyplot   =   chart.getXYPlot(); xyplot.setForegroundAlpha(0.5f);         XYItemRenderer   renderer   =   xyplot.getRenderer();         renderer.setToolTipGenerator(                 new   StandardXYToolTipGenerator(                         StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,                         new   SimpleDateFormat(yyyy-MM),   new   DecimalFormat( "0 ")                 )         );         DateAxis   dateAxis   =   new   DateAxis( "时间 ");         dateAxis.setDateFormatOverride(new   SimpleDateFormat( "yyyy-MM "));         dateAxis.setAutoRange(true);         dateAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);         xyplot.setDomainAxis(dateAxis); ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 1024, 768, null); 

 

下面是显示了有图例的图片,当点比较多时,图例会把生成的图片挤得非常ugly

下面是无图例的图片,由于图片上只画有一组数据,因此不需要用图例来区分不同的曲线。从图片效果来看,还是比较pretty的

完整的程序是一个servlet,需要配置好Tomcat或其他服务器才能运行。
实际上整个过程就是生成一个png图片,然后嵌入到网页中。

目前的问题是,程序只能生成静态的图片,不能产生与用户的交互性效果,比如鼠标移到曲线上某点,能显示出该点的坐标,暂时没有找到好的解决办法。

点击下载完整的程序和测试数据