Import data from a txt file to sagemath and plot it

Question:

I have data in a ‘txt’ file of the form

                       2     ;      4
                       3     ;      -8
                       5     ;       4
                    next prime      ...

So I am trying to import this data as a sequence (a_p)_{p, prime} to sagemath in order to plot it.

So I wrote the following code in ‘file.sage’

a = open('/home/user/tmp/DataFile', 'r')

ap=[]
line=a.readline()
while(line !=''): 
    b=line.split(';')
    ap.append(integer(b[1]))
    line=f.readline()

But the problem is the list ‘ap’ is not indexed only by prime numbers, which hardens the task of plotting the function f(x):=cardinality of {ple x : a_p, satisfies some constraints }. So, I would be grateful if anyone could help me with this.

Asked By: user20534036

||

Answers:

You could do something like this (taking some code and ideas from comments from @OM2220):

ap = {}
with open('/path/to/DATA.txt', 'r') as f:
    for line in f:
        p,q = line.strip().split(';')
        ap[int(p)] = int(q)
list_plot(ap)

Then ap will be a dictionary with keys taken from the left column (prime numbers, in this case), values the right column. Then in Sage you can do list_plot(ap).

Answered By: John Palmieri
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.