Có, nó có thể. Ý tưởng là thay thế mặc định plt.figure
bằng một tùy chỉnh (một kỹ thuật được gọi là monkey patching) sẽ đưa trình xử lý bàn phím sao chép vào khay nhớ tạm. Các mã sau đây sẽ cho phép bạn sao chép bất kỳ con số MPL vào clipboard bằng cách nhấn tổ hợp phím Ctrl + C:
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()
Lưu ý rằng nếu bạn muốn sử dụng from matplotlib.pyplot import *
(ví dụ như trong một phiên tương tác), bạn cần phải làm như vậy sau bạn đã thực thi mã trên, nếu không, figure
bạn nhập vào không gian tên mặc định sẽ là phiên bản chưa được vá.