Reputation: 11
hi im trying to read a text file that gives me coordinates that I need to plot on a 2d list. my text file is simple and contains the plots with x,y for each line already. this is what it looks contains:
3,2
3,3
3,4
4,4
4,5
4,6
so far I've been able to extract the coordinates from the file but I'm stuck on how to get the tuples plotted. here's my code:
fnhandle = open(file_name)
lines = fnhandle.readlines()
lines = [item.rstrip("\n") for item in lines]
r_c_coordinates = list()
for item in lines:
item = item.split(",")
item = tuple(int(items) for items in item)
r_c_coordinates.append(item)
fnhandle.close()
edit: by "plot" I mean that I have an initialized 2d list that contains 0's. i have to go back to the 2d list at the coordinates of the tuples and change these to 1's
Upvotes: 1
Views: 1074
Reputation: 41872
by "plot" I mean that I have an initialized 2d list that contains 0's. i have to go back to the 2d list at the coordinates of the tuples and change these to 1's
An example of plotting points in a grid in memory:
file_name = "points.txt"
my_grid = [[0] * 10 for _ in range(10)] # 10 by 10 grid of zeros
def print_grid(grid):
for row in grid:
print(*row)
print_grid(my_grid)
r_c_coordinates = list()
with open(file_name) as file:
for line in file:
coordinate = [int(n) for n in line.rstrip().split(',')]
r_c_coordinates.append(tuple(coordinate))
for row, column in r_c_coordinates:
my_grid[column][row] = 1
print('- ' * len(my_grid[0]))
print_grid(my_grid)
I'm assuming zero-based coordinates.
OUTPUT (with annotation)
> python3 test.py
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
- - - - - - - - - -
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 # 3,2
0 0 0 1 0 0 0 0 0 0 # 3,3
0 0 0 1 1 0 0 0 0 0 # 3,4 & 4,4
0 0 0 0 1 0 0 0 0 0 # 4,5
0 0 0 0 1 0 0 0 0 0 # 4,6
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
>
Upvotes: 0
Reputation: 1952
If by "plot", you mean on a 2D graph, this is probably the simplest way:
import matplotlib.pyplot as plt
x_coords = [coord[0] for coord in r_c_coordinates]
y_coords = [coord[1] for coord in r_c_coordinates]
plt.plot(x_coords, y_coords, "k.", lw=0)
Upvotes: 2