Home > Enterprise >  Open txt file, take x,y values and do graph with them
Open txt file, take x,y values and do graph with them

Time:11-06

I have to open file and draw a graph with values from this file. I only manage to open file with openfiledialog(), choose file and show valaues in richtextbox. I am not sure how to separete x.y values.

I have two files to use and there could be random amount of values, they looks like this:

What is the best way to seperate x,y and plot graph?

CodePudding user response:

It depends what library for drawing plots expects. But if you need to replace spaces with some other separator, you can do this

listOfValues = File.ReadAllLines("pathToFile.extension");
var formattedValues = new List<string>(listOfValues.Count);
listOfValues.ForEach(x => 
{
   formattedValues.Add(x.Replace(' ', yourCustomStringSeparator))
}

CodePudding user response:

Here's a quick way to get an IEnumerable<(double x, double y)> containing your coordinates, where filename.txt is the name of the file containing your data:

var coordinates = File.ReadAllLines("filename.txt")
       .Select(line => line.Split(' '))
       .Select(line => (x: double.Parse(line[0]), y: double.Parse(line[1])));

Note that this doesn't account for parsing errors, empty lines, etc. You'd want to make this more robust for "production quality" code.

From here, you'll be somewhat dependent on what your charting library expects. This SO answer might be helpful for some more information, although it's a few years old and may no longer be relevant.

CodePudding user response:

String.Split() and Double.Parse() to the rescue:

// Prepare some sample data
string sample="34.200250 85.0\r\n34.0202750 97.0";
// Get a culture that matches the input format
CultureInfo usCulture = new CultureInfo("en-US");
NumberFormatInfo decimalDotFormat = usCulture.NumberFormat;
// Split the whole data to get individual lines
foreach(string line in sample.Split(new[]{"\r","\n"}, StringSplitOptions.RemoveEmptyEntries))
{
   // Split the line again to get X and Y
   var values = line.Split(new[]{" "}, StringSplitOptions.RemoveEmptyEntries);
   double x = double.Parse(values[0], decimalDotFormat);
   double y = double.Parse(values[1], decimalDotFormat);
   // draw using x and y
}
  • Related