How to plot values from a .txt in Julia

Viewed 159

I have a .txt files subdivided in two columns for each axis.

enter image description here

Instead of typing each value like the image below I want Julia to do this tedious job for me and create the same plot as below.

input = [[0,1007], [0.02,1038], [0.04,413], [0.07,50]]

plot([x for (x, y) in input], [y for (x, y) in input])

enter image description here

I am not sure how I can "transfer" the values from the .txt file to Julia

1 Answers

This is the purpose of the DelimitedFiles standard library.

julia> using DelimitedFiles

julia> v = readdlm("xyvals.txt"; skipstart=2)
4×2 Matrix{Float64}:
 0.0    100.0
 0.02  1038.0
 0.04   413.0
 0.07    50.0

julia> plot(v[:, 1], v[:, 2])

The skipstart=2 tells readdlm to skip past the line containing the x-Axis y-Axis text, since that isn't part of the data to be plotted. readdlm is smart enough to figure out that the data is space-separated, and made of floating point values, so returns a 4×2 Matrix{Float64}.

From that, v[:, 1] (the first column's values) is passed in as the x coordinates for the plot, and v[:, 2] makes the y coordinates.

Related