如何使用文本文件中的数据集在Java中绘制折线图?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用文本文件中的数据集在Java中绘制折线图?相关的知识,希望对你有一定的参考价值。

我编写了一个Java GUI程序,它打开一个文本文件并读取左侧面板中的数据。现在我想在右侧面板上显示从同一文件中读取的数据图表。

我使用JFileChooser打开文件并读取数据并将其显示在文本区域。我希望使用二维X-Y图显示从文件读取的数据。应使用数据文件中指定的标签信息标记图表的轴。 X轴上的值应从指定的x轴起始值开始,其间隔以x轴间隔值确定的速率递增。 Y轴上的值需要根据数据本身确定。绘制在图表上的每个点应使用单行连接。

我使用了几种方法,但都没有用。我已经尝试将文本文件中的每一行作为数组读取并使用数组作为数据集,但它也不能正常工作。请帮我从文本文件中的数据绘制图表。任何帮助,将不胜感激。谢谢。

P.S图表应仅使用AWT / Swing库绘制。

该文件的数据如下:

Title: Effect of Age on Ability
Xlabel: Age
Ylabel: Ability
start: 0
interval: 15
0, 3, 4.2, 7, 5.1, 10, 3.2

以下是我到目前为止编写的代码:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

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.general.DefaultPieDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

@SuppressWarnings("serial")
public class GUI extends JFrame {

    private String[] readLines = new String[6];

    public GUI() {
        // Setting Title, size and layout
        setTitle("Data Visualiser");
        setSize(950, 1000);
        setLayout(new BorderLayout());

        // Creates a menubar for a JFrame
        final JMenuBar menuBar = new JMenuBar();

        // Add the menubar to the frame
        setJMenuBar(menuBar);

        // Define and add two drop down menu to the menubar, "file" and "help"
        JMenu fileMenu = new JMenu("File");
        JMenu helpMenu = new JMenu("Help");
        menuBar.add(fileMenu);
        menuBar.add(helpMenu);

        // adding menu items and icons to the "file" drop down menu,
        final JMenuItem openAction = new JMenuItem("Open", new ImageIcon("images/Open-icon.png"));

        final JMenuItem saveAction = new JMenuItem("Save", new ImageIcon("images/save-file.png"));

        final JMenuItem exitAction = new JMenuItem("Exit", new ImageIcon("images/exit-icon.png"));

        final JMenuItem aboutAction = new JMenuItem("About", new ImageIcon("images/about-us.png"));

        //////////////////////////////////////////////////////////////////////////////////////////////
        // Create a text area.
        final JTextArea textArea = new JTextArea("");
        textArea.setFont(new Font("Serif", Font.BOLD, 16));
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setEditable(false);
        JScrollPane textScrollPane = new JScrollPane(textArea);
        // textArea.add(textScrollPane, BorderLayout.CENTER); //add the
        // JScrollPane to the panel

        // Scrollbars
        textScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        textScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        textScrollPane.setPreferredSize(new Dimension(350, 550));
        textScrollPane.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Textual Representation"),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        // Create an graphics pane.
        JPanel graphicsArea = new JPanel();
        //graphicsArea.setFont(new Font("Serif", Font.BOLD, 16));
        JScrollPane graphicsScrollPane = new JScrollPane(graphicsArea);

        // Scrollbars
        graphicsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        graphicsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        graphicsScrollPane.setPreferredSize(new Dimension(550, 550));
        graphicsScrollPane.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Graphical Representation"),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        // Put the graphics pane and the text pane in a split pane.
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsScrollPane);
        splitPane.setOneTouchExpandable(true);
        splitPane.setResizeWeight(0.5);

        JPanel rightPane = new JPanel(new GridLayout(1, 0));
        rightPane.add(splitPane);

        // Put everything together.
        JPanel leftPane = new JPanel(new BorderLayout());
        add(rightPane, BorderLayout.LINE_END);

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // file menu shortcut
        fileMenu.setMnemonic(KeyEvent.VK_F);

        fileMenu.add(openAction);
        // openAction.addActionListener(this);
        openAction.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                if (arg0.getSource().equals(openAction)) {

                    // using JFileChooser to open the text file
                    JFileChooser fileChooser = new JFileChooser();

                    if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
                        // fileChooser.setCurrentDirectory(new
                        // File(System.getProperty("user.home"))); // setting
                        // current
                        // directory
                        File file = fileChooser.getSelectedFile();
                        BufferedReader br = null;

                        try {
                            // FileReader fr = new FileReader(file);
                            Scanner f = new Scanner(file);
                            for (int i = 0; i < 6; i++) {
                                readLines[i] = f.nextLine();
                                textArea.setText(textArea.getText() + readLines[i] + "
");
                                String array[] = readLines[i].split(" ");

                            }
                        } catch (FileNotFoundException e) {
                            JOptionPane.showMessageDialog(new JFrame(), "File not found!", "ERROR!",
                                JOptionPane.ERROR_MESSAGE); // error message
                            // if file not
                            // found
                        } catch (NullPointerException e) {
                            // System.out.println(e.getLocalizedMessage());
                        } finally {
                            if (br != null) {
                                try {
                                    br.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    }
                }
            }
        });

        fileMenu.add(saveAction);
        fileMenu.add(exitAction);

        // exit button shortcut
        exitAction.setMnemonic(KeyEvent.VK_X);
        exitAction.addActionListener(new ActionListener() {

            // setting up exit button
            public void actionPerformed(ActionEvent arg0) {
                if (arg0.getSource().equals(exitAction)) {
                    System.exit(0);
                }
            }
        });

        fileMenu.addSeparator();

        helpMenu.addSeparator();
        helpMenu.add(aboutAction);

        // about button shortcut
        aboutAction.setMnemonic(KeyEvent.VK_A);
        aboutAction.addActionListener(new ActionListener() {

            // clicking on about button opens up a dialog box which contain
            // information about the program
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(menuBar.getComponent(0),
                    "This program is based on the development of a data visualization tool. 
"
                    + "The basic concept is to produce a piece of software which reads in raw textual data, 
"
                    + "analyses that data, then presents it graphically to the user.",
                    "About Us", JOptionPane.PLAIN_MESSAGE);
            }
        });

    }
}
答案

从您的示例开始,请注意以下事项:

  • 使用ChartPanel为你的graphicsArea;那么,你的openAction()可以简单地调用setChart()
  • creatChart()中解析所选文件;显示标题和数据行,但剩余的属性留作练习。
  • 考虑使用Properties作为您的文件格式;
  • 为了获得更大的灵活性,请使用Action,如here所示。
  • 要更改图表面板的默认大小,请覆盖getPreferredSize(),如图所示here
  • 应该仅在event dispatch thread上构造和操作Swing GUI对象。

附:应仅使用AWT / Swing库绘制图表。

对于单个图表,将ChartPanel替换为JPanel并覆盖paintComponent()以执行渲染。您可以使用herehere概述的方法转换坐标。

image

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

//* @see https://stackoverflow.com/a/36764715/230513 */
public class GUI extends JFrame {

    public GUI() {
        super("Data Visualiser");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        final JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        JMenu fileMenu = new JMenu("File");
        JMenu helpMenu = new JMenu("Help");
        menuBar.add(fileMenu);
        menuBar.add(helpMenu);

        final JMenuItem openAction = new JMenuItem("Open", new ImageIcon("images/Open-icon.png"));
        final JMenuItem saveAction = new JMenuItem("Save", new ImageIcon("images/save-file.png"));
        final JMenuItem exitAction = new JMenuItem("Exit", new ImageIcon("images/exit-icon.png"));
        final JMenuItem aboutAction = new JMenuItem("About", new ImageIcon("images/about-us.png"));

        final JTextArea textArea = new JTextArea(8, 16);
        textArea.setFont(new Font("Serif", Font.BOLD, 16));
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setEditable(false);
        JScrollPane textScrollPane = new JScrollPane(textArea);
        textScrollPane.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Textual Representation"),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        ChartPanel graphicsArea = new ChartPanel(null);
        graphicsArea.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Graphical Representation"),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsArea);
        splitPane.setOneTouchExpandable(true);
        splitPane.setResizeWeight(0.5);
        add(splitPane, BorderLayout.LINE_END);

        fileMenu.setMnemonic(KeyEvent.VK_F);
        fileMenu.add(openAction);
        openAction.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (arg0.getSource().equals(openAction)) {
                    JFileChooser fileChooser = new JFileChooser(new File("."));
                    if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
                        File file = fileChooser.getSelectedFile();
                        graphicsArea.setChart(creatChart(file));
                    }
                }
            }

            private JFreeChart creatChart(File file) {
                String title = null;
                String xAxisLabel = null;
                String yAxisLabel = null;
                BufferedReader in = null;
                int start = 0;
                int interval = 0;
                String data = null;
                String line = null;
                try {
                    in = new BufferedReader(new FileReader(file));
                    while ((line = in.readLine()) != null) {
                        textArea.append(line + "
");
                        if (line.startsWith("Title")) {
                            title = line.split(":")[1].trim();
                        }
                        // parse other lines here
                        if (!line.contains(":")) {
                            data = line;
                        }
                    }
                } catch (IOException ex) {
                    ex.printStackTrace(System.err);
                }
                XYSeries dataset = new XYSeries(file.getName());
                for (String s : data.split(",")) {
                    dataset.add(start, Double.valueOf(s));
                    start += interval;
                }
                return ChartFactory.createXYLineChart(title,
                    xAxisLabel, yAxisLabel, new XYSeriesCollection(dataset));
            }
        });
        fileMenu.add(saveAction);
        fileMenu.add(exitAction);
        exitAction.setMnemonic(KeyEvent.VK_X);
        exitAction.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (arg0.getSource().equals(exitAction)) {
                    System.exit(0);
                }
            }
        });
        fileMenu.addSeparator();
        helpMenu.addSeparator();
        helpMenu.add(aboutAction);
        aboutAction.setMnemonic(KeyEvent.VK_A);
        aboutAction.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(null,
                    "Visualization tool.",
                    "About Us", JOptionPane.PLAIN_MESSAGE);
            }
        });
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new GUI();
        });
    }
}

以上是关于如何使用文本文件中的数据集在Java中绘制折线图?的主要内容,如果未能解决你的问题,请参考以下文章

当值为文本时如何在 Power BI 中创建折线图(好的,不正确)?

VB6.0中MSChart调用数据库数据绘制折线图,代码一直有问题。没有接触过MSChart控件,希望大神多多指点!

qml 使用中继器从 Qlist 绘制折线图

Python中matplotlib绘制折线图方法总结

如何从 Pandas 数据框中绘制多个折线图

散景折线图未绘制完整的熊猫数据框