# 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)
~~~

>[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更改時,繪圖會自動更新:

## 屬性
大小,位置和其他屬性可以在[`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()
~~~