gpt4 book ai didi

matplotlib - 如何在 Google Colab 中使用 matplotlib 绘制交互式可绘制图像?

转载 作者:行者123 更新时间:2023-12-05 07:24:36 33 4
gpt4 key购买 nike

我正在尝试绘制一个交互式图像,它可以让我在 Google Colab Notebook 的输出中画线。我尝试使用以下代码。它在我本地的 Jupyter Notebook 中运行良好,但在 Google colab 中不起作用。

有人可以就此提出任何解决方法吗?

还尝试添加 %matplotlib inline,但它显示的是静止图像。

from matplotlib.lines import Line2D
%pylab notebook
%matplotlib inline
#This is needed for plot widgets

class Annotator(object):
def __init__(self, axes):
self.axes = axes

self.xdata = []
self.ydata = []
self.xy = []
self.drawon = False

def mouse_move(self, event):
if not event.inaxes:
return

x, y = event.xdata, event.ydata
if self.drawon:
self.xdata.append(x)
self.ydata.append(y)
self.xy.append((int(x),int(y)))
line = Line2D(self.xdata,self.ydata)
line.set_color('r')
self.axes.add_line(line)

plt.draw()

def mouse_release(self, event):
# Erase x and y data for new line
self.xdata = []
self.ydata = []
self.drawon = False

def mouse_press(self, event):
self.drawon = True


img = np.zeros((28,28,3),dtype='uint8')

fig, axes = plt.subplots(figsize=(3,3))
axes.imshow(img)
plt.axis("off")
plt.gray()
annotator = Annotator(axes)
plt.connect('motion_notify_event', annotator.mouse_move)
plt.connect('button_release_event', annotator.mouse_release)
plt.connect('button_press_event', annotator.mouse_press)

axes.plot()

plt.show()

我希望输出在 Google Colab 中是交互式的,就像我 PC 中的 Jupyter notebook 一样,但输出仍然是图像,无法在其上绘制任何内容。

最佳答案

首先,您必须使用 Google Drive 中的目录安装 colab。你可以试试:

fig = plt.figure()
fig.savefig("your_file_name.png")

from IPython.display import Image
Image("your_file_name.png")

关于matplotlib - 如何在 Google Colab 中使用 matplotlib 绘制交互式可绘制图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55324129/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com