如何更改交互式缩放矩形的颜色?

tit*_*jan 6 python matplotlib

我有一个简单的交互式情节。当我点击放大镜按钮时,我可以绘制一个矩形来进行交互式缩放。您可以在下图中看到虚线矩形。

在此处输入图片说明

但是,当我在深色背景上使用白色网格(带有plt.style.use('dark_background'))时,缩放矩形几乎不可见。它仍然存在,但在一个主要是黑色的情节上是黑色的。

在此处输入图片说明

为完整起见,使用 Matplotlib 3.1.3 生成的图如下:

import matplotlib.pyplot as plt
import numpy as np

plt.style.use('dark_background')

fig = plt.figure()
ax = fig.add_subplot(111)

data = 2.5 * np.random.randn(400) + 3
ax.plot(data)
plt.show()
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:如何更改缩放矩形的颜色?

Pét*_*eéh 2

这取决于您使用的后端,没有(至少我不知道)通用解决方案。正如评论中所述,这只能通过猴子修补来实现。这是我使用 Qt5 后端的尝试。请注意,您还需要安装 PyQt5 才能正常工作。

from PyQt5 import QtGui, QtCore
from matplotlib.backends.backend_qt5 import FigureCanvasQT

# extending the original FigureCanvasQT class

class NewFigureCanvasQT(FigureCanvasQT):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def drawRectangle(self, rect):
        # Draw the zoom rectangle to the QPainter.  _draw_rect_callback needs
        # to be called at the end of paintEvent.
        if rect is not None:
            def _draw_rect_callback(painter):
                pen = QtGui.QPen(QtCore.Qt.red, 1 / self._dpi_ratio, # <-- change the color here
                                 QtCore.Qt.DotLine)
                painter.setPen(pen)
                painter.drawRect(*(pt / self._dpi_ratio for pt in rect))
        else:
            def _draw_rect_callback(painter):
                return
        self._draw_rect_callback = _draw_rect_callback
        self.update()

# do the imports and replace the old FigureCanvasQT
import matplotlib
import matplotlib.pyplot as plt
matplotlib.backends.backend_qt5.FigureCanvasQT = NewFigureCanvasQT
# switch backend and setup the dark background
matplotlib.use('Qt5Agg')
matplotlib.style.use('dark_background')

# do the plotting
plt.plot(range(9))
plt.show()
Run Code Online (Sandbox Code Playgroud)

产生以下图片: 结果

编辑:这似乎在 3.3.1 版本中得到了修复。请参阅发行说明。