Python,matplotlib,通过设置为属性的点散布对象

Python, matplotlib, scatter objects via the points set as attributes

我有包含 x 坐标、y 坐标和一些其他信息(例如颜色)的对象:

import numpy as np
import matplotlib.pyplot as plt

N = 10


class Point:
    def __init__(self, x_axis, y_axis, color, add_info):
        self.x_axis = x_axis
        self.y_axis = y_axis
        self.color = color
        self.add_info = add_info


points = np.empty([N], dtype=Point)

for i in range(N):
    points[i] = Point(np.random.uniform(0, 1), np.random.uniform(0, 1), 'red', 1) # only exemplary 'red' and 1 here

如何分散这些对象,即点,例如将点的颜色设置为红色,if color == 'red'?

我是使用 matplot 的初学者,到目前为止我尝试过的方法都导致了语法错误...谢谢!

plt.scatter 需要一个 x 坐标数组(或列表)和一个 y 坐标数组。可以选择设置一组颜色。对于给定的 Class,代码可能如下所示:

import numpy as np
import matplotlib.pyplot as plt

class Point:
    def __init__(self, x_axis, y_axis, color, add_info):
        self.x_axis = x_axis
        self.y_axis = y_axis
        self.color = color
        self.add_info = add_info

N = 10
points = np.empty([N], dtype=Point)

for i in range(N):
    points[i] = Point(np.random.uniform(0, 1), np.random.uniform(0, 1),
                      np.random.choice(['red', 'green', 'blue', 'magenta']), 1)

plt.scatter([p.x_axis for p in points], [p.y_axis for p in points], c=[p.color for p in points])
plt.show()

虽然这是一个研究 classes 工作原理的有趣示例,但这 存储单点的方式在内存使用和时间方面相当低效。 点数较多或需要精细计算时不建议使用。

如果需要,class 也可以获得绘图功能。当有数千个点时,这会变得非常慢,但可以用几个点来展示概念。另请注意,在 Python 中,列表很少使用索引遍历,而是直接遍历值:

import numpy as np
import matplotlib.pyplot as plt

class Point:
    def __init__(self, x_axis, y_axis, color, add_info):
        self.x_axis = x_axis
        self.y_axis = y_axis
        self.color = color
        self.add_info = add_info

    def draw(self):
        plt.scatter(self.x_axis, self.y_axis, c=self.color)

N = 10
points = [Point(np.random.uniform(0, 1), np.random.uniform(0, 1),
                      np.random.choice(['red', 'green', 'blue', 'magenta']), 1) for _ in range(N)]
for p in points:
    p.draw()
plt.show()