ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# Matplotlib 使用[`pictures.add()`](api.md),可以很容易地将Matplotlib图作为图片粘贴到Excel中。 ## 入门 最简单的样本归结为: ~~~ >>> import matplotlib.pyplot as plt >>> import xlwings as xw >>> fig = plt.figure() >>> plt.plot([1, 2, 3]) >>> sht = xw.Book().sheets[0] >>> sht.pictures.add(fig, name='MyPlot', update=True) ~~~ ![](https://i.vgy.me/zwHQZo.png) >[info]注意 如果你设置`update = True`,你可以在Excel上调整大小并定位图:后续调用同名的`pictures.add()`(`'MyPlot'`)会更新图片而不改变它的位置或大小。 ## 与Excel完全集成 用[RunPython](vba.md)调用上述代码并将其绑定到按钮,这很简单,而且跨平台工作。 但是,在Windows上,您可以通过以下行设置[UDF](udfs.md)来使事物更加集成: ~~~ @xw.func def myplot(n): sht = xw.Book.caller().sheets.active fig = plt.figure() plt.plot(range(int(n))) sht.pictures.add(fig, name='MyPlot', update=True) return 'Plotted with n={}'.format(n) ~~~ 如果导入此函数并从单元格B2调用它,则当单元格B1更改时,绘图会自动更新: ![](https://i.vgy.me/r17TWs.png) ## 属性 大小,位置和其他属性可以在[`pictures.add()`](api.md)中设置为参数,或者通过操作图片 返回的对象,参见[`xlwings.Picture()`](api.md)。 例如: ~~~ >>> sht = xw.Book().sheets[0] >>> sht.pictures.add(fig, name='MyPlot', update=True, left=sht.range('B5').left, top=sht.range('B5').top) ~~~ 或: ~~~ >>> plot = sht.pictures.add(fig, name='MyPlot', update=True) >>> plot.height /= 2 >>> plot.width /= 2 ~~~ ## 得到一个Matplotlib数字 以下是一些如何获得matplotlib“figure”对象的示例: * 通过PyPlot界面: ~~~ import matplotlib.pyplot as plt fig = plt.figure() plt.plot([1, 2, 3, 4, 5]) ~~~ 或: ~~~ import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4, 5]) fig = plt.gcf() ~~~ * 通过面向对象的接口: ~~~ from matplotlib.figure import Figure fig = Figure(figsize=(8, 6)) ax = fig.add_subplot(111) ax.plot([1, 2, 3, 4, 5]) ~~~ * 通过Pandas: ~~~ import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) ax = df.plot(kind='bar') fig = ax.get_figure() ~~~