简体   繁体   English

如何在二维列表(python)上 plot 元组

[英]how to plot tuples on 2d list (python)

hi im trying to read a text file that gives me coordinates that I need to plot on a 2d list.嗨,我正在尝试读取一个文本文件,该文件为我提供了二维列表上 plot 所需的坐标。 my text file is simple and contains the plots with x,y for each line already.我的文本文件很简单,并且已经包含每行带有 x,y 的图。 this is what it looks contains:这是它看起来包含的内容:

3,2 3,2

3,3 3,3

3,4 3,4

4,4 4,4

4,5 4,5

4,6 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.编辑:“情节”是指我有一个包含 0 的初始化二维列表。 i have to go back to the 2d list at the coordinates of the tuples and change these to 1's我必须将 go 回到元组坐标处的二维列表并将这些更改为 1

If by "plot", you mean on a 2D graph, this is probably the simplest way:如果通过“绘图”,您的意思是在 2D 图形上,这可能是最简单的方法:

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)

by "plot" I mean that I have an initialized 2d list that contains 0's. “情节”是指我有一个包含 0 的初始化二维列表。 i have to go back to the 2d list at the coordinates of the tuples and change these to 1's我必须将 go 回到元组坐标处的二维列表并将这些更改为 1

An example of plotting points in a grid in memory:在 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) OUTPUT(带注释)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM