如何为Matplotlib数字添加剪贴板支持?

Eel*_*aak 7 python clipboard plot matplotlib scipy

在MATLAB中,有一个非常方便的选项可以将当前图形复制到剪贴板.虽然Python/numpy/scipy/matplotlib是MATLAB的一个很好的替代品,但遗憾的是这样的选项丢失了.

这个选项可以轻松添加到Matplotlib数字中吗?优选地,所有MPL数字应该自动受益于该功能.

我正在使用MPL的Qt4Agg后端和PySide.

Eel*_*aak 8

是的,它可以.我们的想法是plt.figure用一个自定义的(一种称为猴子修补的技术)替换默认值,该默认注入键盘处理程序以便复制到剪贴板.以下代码允许您通过按Ctrl + C将任何MPL图形复制到剪贴板:

import io
import matplotlib.pyplot as plt
from PySide.QtGui import QApplication, QImage

def add_clipboard_to_figures():
    # use monkey-patching to replace the original plt.figure() function with
    # our own, which supports clipboard-copying
    oldfig = plt.figure

    def newfig(*args, **kwargs):
        fig = oldfig(*args, **kwargs)
        def clipboard_handler(event):
            if event.key == 'ctrl+c':
                # store the image in a buffer using savefig(), this has the
                # advantage of applying all the default savefig parameters
                # such as background color; those would be ignored if you simply
                # grab the canvas using Qt
                buf = io.BytesIO()
                fig.savefig(buf)
                QApplication.clipboard().setImage(QImage.fromData(buf.getvalue()))
                buf.close()

        fig.canvas.mpl_connect('key_press_event', clipboard_handler)
        return fig

    plt.figure = newfig

add_clipboard_to_figures()
Run Code Online (Sandbox Code Playgroud)

请注意,如果要使用from matplotlib.pyplot import *(例如在交互式会话中),则需要在执行上述代码执行此操作,否则figure导入默认命名空间的将是未修补的版本.


Vai*_*aro 5

EelkeSpaak 的解决方案包含在一个不错的模块中: addcopyfighandler

只需通过 安装pip install addcopyfighandler,并在导入 matplotlib 或 pyplot 后导入模块。