如何将 matplotlib 子图复制到剪贴板?

问题描述 投票:0回答:1

在matplotlib中,我们可以使用以下方式将整个图形复制到剪贴板。

def Copy_to_Clipboard(self, event=None):
        """Copy bitmap of canvas to system clipboard."""
        bmp_obj = wx.BitmapDataObject()
        bmp_obj.SetBitmap(self.bitmap)

        if not wx.TheClipboard.IsOpened():
            open_success = wx.TheClipboard.Open()
            if open_success:
                wx.TheClipboard.SetData(bmp_obj)
                wx.TheClipboard.Flush()
                wx.TheClipboard.Close()

https://github.com/matplotlib/matplotlib/blob/302fd39a0fe373aa905e8c273b9f6d9f0020485a/lib/matplotlib/backends/backend_wx.py#L516

有没有办法将子图复制到剪贴板?例如,复制 ax2 的相应子图。谢谢!

fig = plt.figure()
gs0 = fig.add_gridspec(3, 1)
ax1 = fig.add_subplot(gs0[0])
ax2 = fig.add_subplot(gs0[1])
ax3 = fig.add_subplot(gs0[2])
...

检查了axes类,找不到任何线索;也用谷歌搜索,没有运气。

matplotlib clipboard axis subplot
1个回答
0
投票

我想我明白了。例如,

fig = plt.figure()
gs0 = fig.add_gridspec(3, 1)
ax1 = fig.add_subplot(gs0[0])
ax2 = fig.add_subplot(gs0[1])
ax3 = fig.add_subplot(gs0[2])
ax1.plot([1,2,3,4,5])
ax2.plot([5,4,3,2,1])
ax3.plot([1,2,1,2,1])

fig

保存/复制第二个子图(即 ax2)

import numpy as np
# step 1, get the buffer
buf = np.copy(fig.canvas.buffer_rgba())
h, w, _ = buf.shape

# step 2, get the bounding box
pt = ax2.get_tightbbox().get_points()

# step 3, get the corresponding buf (note, for the bounding box, the origin is bottom left corner
buf2 = np.copy(buf[h-int(pt[1, 1]):h-int(pt[0,1])+1, int(pt[0,0]):int(pt[1,0]+1), :])

# step 4, create a bitmap (e.g., with wxpython)
h, w, _ = buf2.shape
bitmap = wx.Bitmap.FromBufferRGBA(w, h, buf2)

# step 5, save to a file
itmap.SaveFile('ax2.bmp', wx.BITMAP_TYPE_BMP)

# or to save the subplot with PIL
import PIL
img = PIL.Image.fromarray(buf2, 'RGBA')
img.save('pil.png')

# or to use the same way to copy it to the clipboard
# https://github.com/matplotlib/matplotlib/blob/302fd39a0fe373aa905e8c273b9f6d9f0020485a/lib/matplotlib/backends/backend_wx.py#L516

ax2

© www.soinside.com 2019 - 2024. All rights reserved.