Issue
if I have a text file called vertices.txt formatted this way :
5 //this is the number of vertices "V"
1, 10 // these are the x,y coordinates of each vertices so this is for vertice 0
8, 10 // coordinates for 1
10, 8 // coordinates for 2
7, 4 // coordinates for 3
3, 1 // coordiantes for 4. I need the coordinates as I will later plot them using matplotlib
0,1,10 // i, j, k tells you that there is an edge between vi and vj and its weight is k.
1,2,5 // v1,v2,5 and so on for the rest
2,3,25
0,3,3
3,4,8
note: in the .txt file the first line is the number of vertices "V". and lines from line 2 to line V+1 are the x,y coordinates for each vertices. and Lines from line number V+2 to the last line give information about the edges of the graph i,j,k
and I want to get the coordinates x and y in a variable and the edges in a variable so i did this:
fr = open('vertices.txt', 'r')
myarray=[]
tempreadintomemory= fr.read()
myarray= tempreadintomemory.splitlines()
print('temp',tempreadintomemory)
print ('myarray',myarray)
numOfVertices=myarray[0]
print(int(numOfVertices)+1)
cor = myarray[1:int(numOfVertices)+1]
print('cor',cor)
myedges=[]
myedges= myarray[int(numOfVertices) + 1:]
print('edges', myedges)
xx=myedges[1].split(",")
print('splitedges',xx)
print('weight',xx[2])
weights=[]
xx=[]
i = 0
while i < len(myedges):
xx = myedges[i].split(",")
weights.append(xx[2])
i += 1
print('the weights',weights)
but i want to get the myedges to be formated this way ['i','j',k] where i and j to be strings and k to be int
also i'm trying to get the coordinates to be in this formats xCor=[1,8,10,7,3] yCor=[10,10,8,4,1] so what should I change in my code?
Solution
This isn't plotting how you might think it is plotting. You're basically tracing a line from one coordinate to the next. What you actually want to do is create a number of line segments between each of your vertices as defined by your edges.
import matplotlib.pyplot as plt
from matplotlib import collections as mc
def create_vertices_text(coord,i):
return ax.text(coord[0],coord[1], 'V'+str(i))
data = []
with open('vertices.txt') as f:
lines = f.readlines()
for line in lines:
data.append([int(elem) for elem in line.strip().split(',')])
edges = []
vertices = []
for row in data[1:]:
if len(row) > 2:
edges.append(row)
if len(row) == 2:
vertices.append(row)
x_cor = [elem[0] for elem in vertices]
y_cor = [elem[1] for elem in vertices]
mylines = [(vertices[edge[0]], vertices[edge[1]]) for edge in edges]
lc = mc.LineCollection(mylines, colors=['k']*len(mylines), linewidths=2)
fig, ax = plt.subplots()
ax.add_collection(lc)
for i in range(len(vertices)):
create_vertices_text(vertices[i],i)
ax.autoscale()
ax.margins(0.1)
plt.show()
Answered By - M. Small
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.