How to add Matplotlib shape clipboard support?

MATLAB has a very convenient way to copy the current picture to the clipboard. Although Python / numpy / scipy / matplotlib is a great alternative to MATLAB, this option is unfortunately not available.

Can this parameter be easily added to Matplotlib drawings? Preferably, all MPL values ​​automatically benefit from this function.

I am using the Qt4Agg MPL server using PySide.

+7
source share
2 answers

Yes it is possible. The idea is to replace the standard plt.figure with a custom one (a method known as decapitating monkeys ) that introduces a keyboard handler to copy to the clipboard. The following code will allow you to copy any MPL digit to the clipboard by pressing 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() 

Please note that if you want to use from matplotlib.pyplot import * (for example, in an interactive session), you need to do this after executing the above code, otherwise the figure that you import into the default namespace will have an unloaded version.

+8
source

EelkeSpaak solution was packaged in a nice module: addcopyfighandler

Just install pip install addcopyfighandler and import the module after importing matplotlib or pyplot.

0
source

All Articles