0

我已经使用 GNUPLOT 很长时间了,但现在我必须使用 JFreeChart 来实现类。我的 gnuplot 文本文件格式如下:

Name_1 Name_2
1 4
2 4
3 1
4 5
5 3

我在文件“data.txt”中有这些数据,我想使用 JFreeChart 打印图表并将其保存到另一个文件 fe“result.png”。

你能给我一些代码吗?

先感谢您

4

1 回答 1

1

例如,我使用guava lib编写,非常有用。

import java.io.File;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.io.Files;

public class App {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Function<String, double[]> lineToXy = new Function<String, double[]>() {
            @Override
            public double[] apply(String line) {
                String[] s = line.split(" ", 0);
                double x = Double.parseDouble(s[0]);
                double y = Double.parseDouble(s[1]);
                return new double[] { x, y };
            }
        };

        try {
            //input file name is data.txt
            File file = new File("./data.txt");
            List<String> lines = Files.readLines(file, Charsets.UTF_8);
            List<double[]> xyList = Lists.transform(lines, lineToXy);
            XYSeriesCollection data = new XYSeriesCollection();
            XYSeries series = new XYSeries("XY Series");
            for (double[] xy : xyList) {
                series.add(xy[0], xy[1]);
            }
            data.addSeries(series);

            JFreeChart chart = ChartFactory.createXYLineChart("Tilte",
                "xLabel", "yLabel", data, PlotOrientation.VERTICAL, true,
                false, false);
            //output png file name is graph.png
            File png = new File("./graph.png");
            ChartUtilities.saveChartAsPNG(png, chart, 400, 300);
        } catch (Exception e) {
            //error handling
        } finally {
            //file close,and so on.
        }
        System.exit(0);
    }
}
于 2012-05-27T20:35:18.537 回答