Home > database >  Import data from a txt file to sagemath and plot it
Import data from a txt file to sagemath and plot it

Time:12-06

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 {p\le x : a_p, satisfies some constraints }. So, I would be grateful if anyone could help me with this.

CodePudding user response:

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).

  • Related