在 pyqtgraph 中显示图像上的网格线

Show grid lines over image in pyqtgraph

我正在 pyqtgraph 中绘制图像,我希望能够看到网格线。但是网格线总是绘制在图像下方,因此图像的任何黑色区域都会遮挡网格。这是一个相当小的例子:

import matplotlib  # necessary for interactive plots in pyqtgraph
import pyqtgraph as pg
import numpy as np
n = 100000
sigma_y = 1e-3
sigma_x = 1e-3
x0 = np.matrix([np.random.normal(0, sigma_x, n), np.random.normal(0, sigma_y, n)])
bins = 30
histogram, x_edges, y_edges = np.histogram2d(np.asarray(x0)[0], np.asarray(x0)[1], bins)
x_range = x_edges[-1] - x_edges[0]
y_range = y_edges[-1] - y_edges[0]

imv = pg.ImageView(view=pg.PlotItem())
imv.show()
imv.setPredefinedGradient('thermal')
imv.getView().showGrid(True, True)
imv.setImage(histogram, pos=(x_edges[0], y_edges[0]), scale=(x_range / bins, y_range / bins))

这是我看到的(稍微缩小后)。可以看到图片的黑色区域遮挡了网格线。

编辑:可以在 GUI 中将黑色更改为透明(这不是我的第一选择,但目前是一个可行的解决方法),因此您可以看到下面的网格图片。这行得通,但我不知道如何在代码中做到这一点。如何从 ImageView 中获取查找 table 以修改它?

这是我做的。

glw = pyqtgraph.GraphicsLayoutWidget()
pw = glw.addPlot(0, 0)

# Fix Axes ticks and grid
for key in pw.axes:
    ax = pw.getAxis(key)

    # Set the grid opacity
    if grid_is_visible:
        ax.setGrid(grid_opacity * 255)
    else:
        ax.setGrid(False)

    # Fix Z value making the grid on top of the image
    ax.setZValue(1)

我认为这确实导致了一些其他问题。它可能是上下文菜单,或者它与平移和缩放有关,因为 Qt 是如何发出事件信号的。一个轴获得事件优先级并阻止事件传播到其他轴以进行平移和缩放。我向 pyqtgraph 提交了拉取请求,因此这可能不再是问题。我不记得是什么导致了这个问题。它可能适合你。我做了很多其他事情,比如更改背景颜色和更改视图框背景颜色,这导致了一些小问题。

请注意,我还更改了图像的 z 值。不过你不应该这样做。

imv.setZValue(1)