使用opencsv从csv文件向JFreeChart XYDataset添加值

时间:2015-04-17 00:01:37

标签: java csv jfreechart opencsv

我正在尝试读取一个.csv文件,但我一直在阅读csv文件中的每一行以及如何将其添加到XYDataset。

我的算法如下:读入.csv文件 - >阅读每一行 - >添加到数据集 - >创建图表 - >输出为框架

data.csv有4列:TimeXYZ

如何将每个点(时间,x),(时间,y),(时间,z)添加到数据集中?

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

import com.opencsv.CSVReader;

public class Test extends ApplicationFrame
{
    XYDataset dataset;
    JFreeChart chart;
    final ChartPanel chartPanel;
    final int chartWidth = 560;
    final int chartHeight = 367;
    CSVReader reader;
    String[] readNextLine;
    XYSeries series;

   public Test(String applicationTitle) throws IOException 
   {
      super(applicationTitle); 
      dataset = createDataset(); 
      chart = createChart(dataset);   
      chartPanel = new ChartPanel(chart);  
      chartPanel.setPreferredSize(new java.awt.Dimension(chartHeight, chartWidth));  
   }

   public XYDataset createDataset() throws NumberFormatException, IOException
   {
       dataset = new XYSeriesCollection(); 
       try
       {
           reader = new CSVReader(new FileReader("data.csv")); 
           while((readNextLine = reader.readNext()) != null) 
           {
              if (readNextLine != null)
              {
                  //add values to dataset
              }
           }
     } 
     catch (FileNotFoundException e)
     {
         System.out.println("File not found!");
     }
     return dataset;
   }

 public JFreeChart createChart(XYDataset dataset) throws      NumberFormatException, IOException
 {
    chart = ChartFactory.createXYLineChart(
    "Acceleration vs Time",     //chart title 
    "Time",                     //domain axis label
    "Acceleration",             //range axis label
    createDataset(),            //data
    PlotOrientation.VERTICAL,   //the plot orientation
    true,                       //legend
    true,                       //tooltips
    false);                     //urls

return chart;
}

public static void main(String[] args) throws IOException
{
    final Test demo = new Test("Test XY Line chart");
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);
}
}

我的数据集的前10行看起来像这样:

time    x   y   z
0.003   -0.13   0.83    0.6
0.009   -0.12   0.83    0.61
0.012   -0.12   0.82    0.6
0.018   -0.13   0.81    0.61
0.021   -0.13   0.8 0.61
0.025   -0.12   0.8 0.61
0.033   -0.12   0.79    0.6
0.034   -0.11   0.79    0.6
0.039   -0.11   0.79    0.58
0.044   -0.11   0.77    0.57

1 个答案:

答案 0 :(得分:2)

您的评论在哪里 - 您需要首先浏览readNextLine的元素,其中String[]的每个元素都将包含您文件中给定行的值(假设您的文件格式正确)如你所说)。所以 - 你需要把它们变成变量。您尚未指定这些格式的格式,或TimeXYZ的数据类型。

鉴于您正在查看XY图表并且您的轴标有Timeacceleration - 我会猜测他们是所有浮点数,小数点为Time,其他变量为各轴加速度。注 - 如果这个假设是错误的 - 您可能需要使用不同的转换器,例如Integer.valueOf(),但原理是相同的。

while循环之前

,设置要添加到的系列。您将在while循环中逐行添加

final XYSeries seriesX = new XYSeries("X");
final XYSeries seriesY = new XYSeries("Y");
final XYSeries seriesZ = new XYSeries("Z");

while循环中,您的评论为

//add values to dataset
double Time = Double.valueOf(readNextLine[0]);
double X = Double.valueOf(readNextLine[1]);
double Y = Double.valueOf(readNextLine[2]);    
double Z = Double.valueOf(readNextLine[3]);
seriesX.add(Time, X);
seriesY.add(Time, Y);
seriesZ.add(Time, Z);

并在while循环之后将3系列添加到集合中,然后再返回它:

dataset.addSeries(seriesX);
dataset.addSeries(seriesY);
dataset.addSeries(seriesZ);

最后 - 两条评论

  1. 您的逻辑在数据集创建方面有点奇怪。在构造函数中,创建数据集并将其传递给createChart()。这是非常标准的。但是,然后在对ChartFactory.createXYLineChart(的调用中内联调用createDataset(),从而使第一次创建数据毫无意义并再次完成所有操作。它会起作用,但是很浪费,可能会掩盖你打算让代码去做的其他事情。

  2. if签入createDataset()是多余的 - 您已经在基于条件的while循环中,这意味着它始终是真的。

    if (readNextLine != null)
    {
    
  3. 编辑 - 添加了完整的工作版本以清除多条评论中的混淆

    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartPanel;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.data.xy.XYDataset;
    import org.jfree.data.xy.XYSeries;
    import org.jfree.data.xy.XYSeriesCollection;
    import org.jfree.ui.ApplicationFrame;
    import org.jfree.ui.RefineryUtilities;
    
    import au.com.bytecode.opencsv.CSVReader;
    
    public class Test extends ApplicationFrame {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        XYSeriesCollection dataset;
        JFreeChart chart;
        final ChartPanel chartPanel;
        final int chartWidth = 560;
        final int chartHeight = 367;
        CSVReader reader;
        String[] readNextLine;
        XYSeries series;
    
        public Test(String applicationTitle) throws IOException {
            super(applicationTitle);
            dataset = createDataset();
            chart = createChart(dataset);
            chartPanel = new ChartPanel(chart);
            chartPanel.setPreferredSize(new java.awt.Dimension(chartHeight,
                    chartWidth));
            this.add(chartPanel);
        }
    
        public XYSeriesCollection createDataset() throws NumberFormatException,
                IOException {
            dataset = new XYSeriesCollection();
            try {
                reader = new CSVReader(new FileReader("res\\data.csv"),'\t');
                // Read the header and chuck it away
                readNextLine = reader.readNext();
    
                // Set up series
                final XYSeries seriesX = new XYSeries("X");
                final XYSeries seriesY = new XYSeries("Y");
                final XYSeries seriesZ = new XYSeries("Z");
    
                while ((readNextLine = reader.readNext()) != null) {
                    // add values to dataset
                    double Time = Double.valueOf(readNextLine[0]);
                    double X = Double.valueOf(readNextLine[1]);
                    double Y = Double.valueOf(readNextLine[2]);
                    double Z = Double.valueOf(readNextLine[3]);
                    seriesX.add(Time, X);
                    seriesY.add(Time, Y);
                    seriesZ.add(Time, Z);
                }
    
                System.out.println(seriesX.getMaxX() + "; " + seriesX.getMaxY());
    
                dataset.addSeries(seriesX);
                dataset.addSeries(seriesY);
                dataset.addSeries(seriesZ);
            } catch (FileNotFoundException e) {
                System.out.println("File not found!");
            }
            return dataset;
        }
    
        public JFreeChart createChart(XYDataset dataset)
                throws NumberFormatException, IOException {
            chart = ChartFactory.createXYLineChart("Acceleration vs Time", // chart
                                                                            // title
                    "Time", // domain axis label
                    "Acceleration", // range axis label
                    dataset, // data
                    PlotOrientation.VERTICAL, // the plot orientation
                    true, // legend
                    true, // tooltips
                    false); // urls
    
            return chart;
        }
    
        public static void main(String[] args) throws IOException {
            System.out.println("In here, to create a Test");
            final Test demo = new Test("Test XY Line chart");
            System.out.println("Created, pakcking");
            demo.pack();
            RefineryUtilities.centerFrameOnScreen(demo);
            demo.setVisible(true);
        }
    }
    

    输出,OP提供前10个数据点

    acceleration graph output of program