我正在尝试使用 Matplotlib 动态添加矩形到绘图中,但绘图中出现了一些奇怪的线条。
我的网格是一个带有 init 和更新函数的类,用于向绘图添加新的矩形形状
class GridDisplay:
def __init__(self):
# initialize and configure the plot
def UpdatePlotWithIndicesCoords(self, layerID, newData):
# update the plot with a new rectangle
函数的定义如下面的代码片段所示
def UpdatePlotWithIndicesCoords(self, layerID, newData):
x0 = newData[0]
x1 = newData[2]
y0 = round(newData[1], 6)
y1 = round(newData[3], 6)
height = round(y1 - y0, 6)
width = round(x1 - x0, 6)
y = y0
x = x0
self.rectangles.append((x, y, width, height))
self.graph.remove()
rectangle = plt.Rectangle((x, y), width, height, edgecolor='yellow', facecolor=layerID, lw=1)
self.ax.add_patch(rectangle)
self.graph = self.ax.plot(self.rectangles)[0]
def __init__(self):
ySize = 15
xSize = 25
xStart = -6
yStart = -6
xEnd = 5
yEnd = 5
self.fig, self.ax = plt.subplots(figsize=(xSize, ySize))
# Set axis limits
self.ax.set_ylim( yStart, yEnd)
self.ax.set_xlim(xStart, xEnd)
# Change major ticks to show every 0.5
self.ax.xaxis.set_major_locator(MultipleLocator(0.5))
self.ax.yaxis.set_major_locator(MultipleLocator(0.5))
# Change minor ticks to show every 0.1
self.ax.xaxis.set_minor_locator(AutoMinorLocator(0.1))
self.ax.yaxis.set_minor_locator(AutoMinorLocator(0.5))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
self.ax.grid(which='major', color='#CCCCCC', linestyle='--')
self.ax.grid(which='minor', color='#CCCCCC', linestyle=':')
# Set labels and title
self.ax.set_xlabel('h')
self.ax.set_ylabel('v')
self.ax.set_title('S-Cell Routing grid')
# Set grid
self.ax.grid(True)
self.rectangles = []
self.graph = self.ax.plot(self.rectangles)[0]
从另一个包调用
UpdatePlotWithIndicesCoords
函数,该包仅指定矩形的边界坐标 (x0, y0, x1, y1),如下面的代码片段所示
self.gridDisplay.UpdatePlotWithIndicesCoords(layerID, (startX, startY, endX, endY))
layerID参数用于指定矩形的颜色,对于问题来说并不是那么重要
所示图像是由下面的代码生成的,它演示了问题。
import bin.ui.display as GridDisplay
gridDisplay = GridDisplay()
startX = -5
startY = -5
for i in range(1, 6):
layer = str('Metal') + str(i)
newData = (startX + round(i*0.2, 6), startY + round(i*0.5, 6), startX + round(i*0.6, 6), startY + round(i*0.7, 6))
gridDisplay.UpdatePlotWithBoundboxCoords(layer, newData)
我不确定我做错了什么,但我似乎无法弄清楚为什么绘制随机线。
我查阅了有关使用 Matplotlib 动态绘制形状的文档和帖子,但解决方案似乎都不起作用。
对了,我还为Matplotlib启用了交互模式
plt.ion()
谢谢并致以亲切的问候。
就像 @JohanC 所解释的一样,出现四行是因为 Axes.plot(*args, ...)
rectangles
(是 4 元组元素列表)视为要绘制的序列列表。您可以使用这个最小的可重现代码来可视化这一点:
import matplotlib.pyplot as plt
rectangles = [
(-4.8, -4.5, 0.4, 0.2),
(-4.6, -4.0, 0.8, 0.4),
(-4.4, -3.5, 1.2, 0.6),
(-4.2, -3.0, 1.6, 0.8),
(-4.0, -2.5, 2.0, 1.0),
]
plt.plot(rectangles) # gives exactly 4 lines like OP
解决方案是删除下面的行或将图形分配给 调用(如果需要):
self.ax.add_patch(rectangle)
self.graph = self.ax.plot(self.rectangles)[0]