如何更改交互式缩放矩形的颜色? [英] How to change the color of the interactive zoom rectangle?

查看:36
本文介绍了如何更改交互式缩放矩形的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple interactive plot. When I click on the magnifying glass button I can draw a rectangle to do interactive zooming. You can see the dotted rectangle in the image below.

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

However, when I use white grid on a dark background (with plt.style.use('dark_background')), the zoom rectangle is barely visible. It is still there but black on a largely black plot.

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

For completeness, the plots where generated with Matplotlib 3.1.3 as follows:

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

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

So my question therefore is: how can I change the color of the zoom rectangle?

推荐答案

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

It depends on what backend you're using there is no (at least I don't know a) universal solution. As stated in the comments this can be achieved only with monkey-patching. Here is my attempt using Qt5 backend. Note that you need to have PyQt5 installed too in order to make this work.

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

将产生以下图片:

编辑:这似乎在版本3.3.1中已修复.查看发行说明.

EDIT: This seem to be fixed in release 3.3.1. See the release notes.

这篇关于如何更改交互式缩放矩形的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆