3
$\begingroup$

I have the data stored in the textfile like this:

0.5 0.5 -0.7 -0.8

0.51 0.51 -0.75 -0.85

0.6 0.1 0.1 1.00

and so on

4 numbers in each row. Two first numbers means coordinates (x0,y0), two last - (x1,y1). This determines the coordinates of a line. So, the first row tells, that I have a line starting from (0.5, 0.5) and finishing in (-0.7, -0.8). The aim is to plot all of these lines. How can I do this? Explain it for beginner, please.

$\endgroup$
1
  • 1
    $\begingroup$ Well you’ll have to import the data first. What format is it in? Then presuming you get it in some form like {{{x1,y1},{x2,y2}},....} you can just use Line in a Graphics. $\endgroup$ – CA Trevillian Dec 12 '20 at 22:29
3
$\begingroup$

You can use "Table" to keep the structure of your data. And then you define a function Line[{{#1, #2}, {#3, #4}}]& to draw the Line by two points {#1,#2} and {#3,#4}.

0.5 0.5 -0.7 -0.8
0.51 0.51 -0.75 -0.85
0.6 0.1 0.1 1.00
data = Import["data.txt", "Table"]

(* {{0.5, 0.5, -0.7, -0.8}, {0.51, 0.51, -0.75, -0.85}, {0.6, 0.1, 0.1, 
  1.}} *)

Graphics[Line[{{#1, #2}, {#3, #4}}] & @@@ data]

enter image description here

$\endgroup$
1
  • $\begingroup$ Thank you for your guidance! This is a good way to solve this problem indeed! $\endgroup$ – Михаил Кочубей Dec 12 '20 at 23:40
7
$\begingroup$
data = Import["/Users/roberthanlon/Downloads/lines.txt", "Data"]

(* {{0.5, 0.5, -0.7, -0.8}, {0.51, 0.51, -0.75, -0.85}, {0.6, 0.1, 0.1, 1.}} *)

Graphics[Line /@ (Partition[#, 2] & /@ data), Axes -> True]

enter image description here

Highlight any function or operator and press F1 for help.

$\endgroup$
1
  • $\begingroup$ Thank you a million for you prompt reply! You really helped me out! $\endgroup$ – Михаил Кочубей Dec 12 '20 at 23:37
1
$\begingroup$

This is another way to do it:

data = ImportString[
   "0.5 0.5 -0.7 -0.8
0.51 0.51 -0.75 -0.85
0.6 0.1 0.1 1.00", "Table"]
Graphics[
 Table[
  Line[Partition[row, 2]],
  {row, data}
  ]
 ]

Try each piece of the code separately to see what it does (this applies to all situations when you are trying to understand some code). For example, try these and observe the output:

Partition[{0.5, 0.5, -0.7, -0.8}, 2]
Table[
 f[row],
 {row, data}
 ]
Table[
 Line[Partition[row, 2]],
 {row, data}
 ]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.