【问题标题】:C# Read string from CSV file and plot line graphC# 从 CSV 文件中读取字符串并绘制折线图
【发布时间】:2017-05-29 13:45:31
【问题描述】:

目前,我能够从多个 CSV 文件中读取数据并使用 Windows 窗体应用程序绘制折线图。但是,现在我需要根据 CSV 文件的部分名称(csv 文件的第 3 列)绘制折线图。

修改/新建 CSV 文件:(添加了部分名称列)

Values,Sector,Name
5.55,1024,red
5.37,1536,red
5.73,2048,blue
5.62,2560,.blue
5.12,3072,.yellow
...
  1. 基于 Section Name 列,我的折线图需要相应地绘制在 Single line 中,并且必须用不同的颜色绘制不同的部分,包括显示的图例必须根据不同的部分名称显示图表的侧面。
  2. 1 个 csv 文件 = 1 个系列。但是 csv 文件中有相同的部分名称(上面显示的 csv 文件示例,例如红色代表第 20 行)。 相同的部分名称 = 相同的颜色。如果我打开 2 个或更多 csv 文件 = 2 系列。由于 csv 文件中的部分名称不同,每个系列都有不同的颜色。

我是编程新手,非常感谢有人可以通过编辑我的代码来帮助我。

谢谢。

【问题讨论】:

  • 您可以按部分列分隔数据,并使用部分名称作为系列集合的索引,而不是使用i。最好使用部分名称作为 Series.Name!我建议使用包含两个数字和字符串的数据类,并将它们收集在List<Dataclass> 中。然后为distinct 部分创建系列。然后使用chart.Series[data.Section].Points.AddXY(data.N1, data.N2) 遍历它们。
  • 嗨 TaW,你能添加/编辑我的代码并告诉我它是如何完成的吗?刚开始学编程,所以真的不知道改哪个部分
  • 完成。注意第一版的更正。也请使用您自己的数据名称等。
  • 这些颜色是从哪里来的?每个部分的任意颜色?
  • 每个部分可以是随机颜色。主要部分是显示 1csv 文件 - 包含各种部分名称(某些行具有相同的部分名称)显示在 1 系列中。但是那个系列必须有基于各个部分的各种颜色的图例。

标签: c# winforms csv mschart


【解决方案1】:

您可以按部分列分隔数据,并将部分名称用作Series 集合的索引,而不是使用i

最好使用部分名称作为Series.Name。我建议使用包含两个数字和字符串的数据类,并将它们收集在List<Dataclass> 中。然后为不同的部分创建Series。然后循环它们..

以下是一些代码示例:

为您的数据定义一个class

public class Data3
{
    public int N1 { get; set;}
    public double N2 { get; set;}
    public string S1 { get; set;}

    public Data3(double n2, int n1, string s1)
    {
        N1 = n1; N2 = n2; S1 = s1;
    }
}

选择你自己的名字!可选但始终推荐:添加一个不错的 ToString() 重载!

声明一个类级别的变量:

  List<Data3> data = new List<Data3>();

在读取期间收集那里的数据:

  data.Add(new Data3(Convert.ToDouble(pieces[1]), Convert.ToInt32(pieces[0]), pieces[2]));

要绘制图表,首先创建Series:

 var sections= data.Select(x => x.S1).Distinct<string>();
 foreach (string s in sections)
          chart.Series.Add(new Series(s) { ChartType = SeriesChartType.Line });

然后绘制数据;该系列可以通过他们的Names进行索引:

 foreach (var d in data) chart.Series[d.S1].Points.AddXY(d.N1, d.N2);

我忽略了将代码集成到您的应用程序中的细节;如果遇到问题,请通过编辑问题来显示新代码!

几点说明:

  • 如有疑问,请始终创建一个类来保存您的数据

  • 如有疑问,请始终选择类而不是结构

  • 如有疑问,请始终选择 List&lt;T&gt; 而不是数组

  • 始终尝试将代码分解为具有有用名称的小块。

示例:要读取 csv 文件中的所有数据,请创建一个函数来执行此操作:

public void AppendCsvToDataList(string file, List<Data3> list)
{
    if (File.Exists(file))
    {
        var lines = File.ReadAllLines(file);
        for (int l = 1; l < lines.Length; l++)
        {
            var pieces = lines[l].Split(',');
            list.Add(new Data3(Convert.ToInt32(pieces[1]),
                               Convert.ToDouble(pieces[0]), pieces[2]));
        }
    }
}

【讨论】:

  • 您好 TaW,感谢您的回答。我已经尝试添加您的代码,但我不确定我应该将代码插入到哪里。以及我需要移除的部分。
  • 我只编辑了 Read 类(如上所示)。如果您可以从我的代码中进行编辑,那就太好了,真的很困惑我应该将其余代码添加到哪里。
  • 我添加了一个函数来读取一个csv文件的数据。它使用更简单的 File 方法,但如果您出于某种原因需要使用流,您当然可以这样做。我不确定实际需要多少代码。你有错误吗? (我没有看到您的列表声明)。请注意,我的函数会丢弃标题,这可能是也可能不是一个好主意..
  • 设置 ChartArea 是正确的,只要确保你只做一次。不要更改系列的 LegendText,除非您有比部分名称更好的值!其余的似乎没有必要。
  • 但是:请澄清:您想要每个部分名称一个系列还是每个 csv 文件一个系列?这些文件会有共同的部分名称吗??
【解决方案2】:

更新代码:

GraphDemo(表格):

    List<Read> rrList = new List<Read>();

    void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog ff = new OpenFileDialog();
        Read rr;

        ff.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //"C:\\";
        ff.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
        ff.Multiselect = true;
        ff.FilterIndex = 1;
        ff.RestoreDirectory = true;

        if (ff.ShowDialog() == DialogResult.OK)
        {
            try
            {
                rrList.Clear();
                foreach (String file in ff.FileNames) //if ((myStream = ff.OpenFile()) != null)
                {
                    rr = new Read(file);
                    rrList.Add(rr); 
                }

                //Populate the ComboBoxes
                if (rrList.Count > 0)
                {
                    string[] header = rrList[0].header; //header of first file
                    xBox.DataSource = header; 
                    yBox.DataSource = header.Clone(); //without Clone the 2 comboboxes link together!
                }
                if (yBox.Items.Count > 1) yBox.SelectedIndex = 1; //select second item
            }
            catch (Exception err)
            {
                //Inform the user if we can't read the file
                MessageBox.Show(err.Message);
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Plot.Draw(rrList, xBox, yBox, chart);
    }

类阅读:

public class Read
{
    public int nLines { get; private set; }
    public int nColumns { get; private set; }
    public string[] header { get; private set; }
    public float[,] data { get; private set; }
    public string fileName { get; set; }
    public string[] section { get; private set; }

    public Read(string file)
    {
        string[] pieces;

        fileName = Path.GetFileName(file);  
        string[] lines = File.ReadAllLines(file); // read all lines
        if (lines == null || lines.Length < 2) return; //no data in file
        header = lines[0].Split(','); //first line is header
        nLines = lines.Length - 1; //first line is header
        nColumns = header.Length;

        //read the numerical data and section name from the file
        data = new float[nLines, nColumns - 1]; // *** 1 less than nColumns as last col is sectionName
        section = new string[nLines]; // *** 
        for (int i = 0; i < nLines; i++) 
        {
            pieces = lines[i + 1].Split(','); // first line is header
            if (pieces.Length != nColumns) { MessageBox.Show("Invalid data at line " + (i + 2) + " of file " + fileName); return; }
            for (int j = 0; j < nColumns - 1; j++)
            {
                float.TryParse(pieces[j], out data[i, j]); //data[i, j] = float.Parse(pieces[j]);
            }
            section[i] = pieces[nColumns - 1]; //last item is section
        }
    }

}

班级剧情:

public class Plot
{
    //public Plot() { } //no constructor required as we use a static class to be called

    public static void Draw(List<Read> rrList, ComboBox xBox, ComboBox yBox, Chart chart) //***
    {
        int indX = xBox.SelectedIndex;
        int indY = yBox.SelectedIndex;

        chart.Series.Clear(); //ensure that the chart is empty
        chart.Legends.Clear();
        Legend myLegend = chart.Legends.Add("myLegend");
        myLegend.Title = "myTitle";

        //define a set of colors to be used for sections
        Color[] colors = new Color[] { Color.Black, Color.Blue, Color.Red, Color.Green, Color.Magenta, Color.DarkCyan, Color.Chocolate, Color.DarkMagenta }; 

        //use a Dictionary to keep iColor of each section
        // key=sectionName, value=iColor (color index in our colors array)
        var sectionColors = new Dictionary<string, int>();

        int i = 0;
        int iColor = -1, maxColor = -1;
        foreach (Read rr in rrList)
        {
            float[,] data = rr.data;
            int nLines = rr.nLines;
            int nColumns = rr.nColumns;
            string[] header = rr.header;

            chart.Series.Add("Series" + i);
            chart.Series[i].ChartType = SeriesChartType.Line;

            //chart.Series[i].LegendText = rr.fileName;
            chart.Series[i].IsVisibleInLegend = false; //hide default item from legend

            chart.ChartAreas[0].AxisX.LabelStyle.Format = "{F2}";
            chart.ChartAreas[0].AxisX.Title = header[indX];
            chart.ChartAreas[0].AxisY.Title = header[indY];

            for (int j = 0; j < nLines; j++)
            {
                int k = chart.Series[i].Points.AddXY(data[j, indX], data[j, indY]);
                string curSection = rr.section[j];
                if (sectionColors.ContainsKey(curSection))
                {
                    iColor = sectionColors[curSection];
                }
                else
                {
                    maxColor++;
                    iColor = maxColor; sectionColors[curSection] = iColor;
                }
                chart.Series[i].Points[k].Color = colors[iColor];
            }

            i++; //series#

        } //end foreach rr

        //fill custom legends based on sections/colors
        foreach (var x in sectionColors)
        {
            string section = x.Key;
            iColor = x.Value;
            myLegend.CustomItems.Add(colors[iColor], section); //new LegendItem()
        }
    }

}

【讨论】:

  • 好的,我稍后试试。谢谢你的时间!我试过后会告诉你情况如何。
  • 对于图例,我需要在此处显示所有部分名称(基于它们的颜色)或该系列中使用的所有颜色。最佳案例示例:2 个 csv 文件(1 个文件包含 .text、.data、.rdata 部分名称,另一个文件包含 .text、.data、.rsrc 部分名称)。因此,图例将总共显示 4 种颜色(.text、.data、.rdata、.rsrc)。并且会有2个系列(2个文件)
  • 目前,如果我的 csv 文件包含其他部分,我的 GUI 会显示:prntscr.com/dw6lbf,它会显示不同的颜色(这是正确的),但我也需要在图例上显示它。
  • 如果我尝试打开 6 个 csv 文件(仅包含 1 个部分名称,但每个 csv 中有多行),我会得到:prntscr.com/dw6mle,图例似乎已正确指示,但仅图表有 1 种颜色(第一种颜色)。对于包含其他部分名称的 csv 文件,我的图例只显示 csv 文件名,而不是部分名称。
  • 代码更新,每个部分显示不同的颜色。颜色在 Plot 类中指定为Color[] colors = new Color[] { Color.Black, Color.Blue, Color.Red, ...。您必须根据需要添加更多以获取更多部分。但我不知道应该在哪里打印文件名?
猜你喜欢
  • 2015-08-30
  • 1970-01-01
  • 2012-03-17
  • 2017-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
相关资源
最近更新 更多