在MATLAB中,有一个非常方便的选项可以将当前图形复制到剪贴板。尽管 Python/numpy/scipy/matplotlib 是 MATLAB 的一个很好的替代品,但不幸的是缺少这样一个选项。
这个选项可以很容易地添加到 Matplotlib 图形中吗?最好是,所有 MPL 数字都应自动受益于此功能。
我正在使用 MPL 的 Qt4Agg 后端和 PySide。
最佳答案
是的,它可以。这个想法是用一个自定义的(一种称为 monkey patching 的技术)替换默认的 plt.figure
,它注入(inject)一个用于复制到剪贴板的键盘处理程序。以下代码将允许您通过按 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()
请注意,如果您想使用 from matplotlib.pyplot import *
(例如,在交互式 session 中),您需要在执行上述操作后执行此操作代码,否则您导入默认命名空间的 figure
将是未打补丁的版本。
关于python - 如何为 Matplotlib 图形添加剪贴板支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31607458/