简体   繁体   English

如何使用Xlwing和Python在Excel中返回Matplot图表?

[英]How to return a matplot chart in excel using xlwing and Python?

I'm new to Python and Xlwings. 我是Python和Xlwings的新手。 I am trying to create a UDF to return a "BOX plot" in excel. 我正在尝试创建一个UDF以在Excel中返回“箱形图”。 Table in Excel has two columns "Sales_Region" and "Total Sales". Excel中的表具有两列“ Sales_Region”和“ Total Sales”。

On running the below code, I am getting the error "Object required". 在运行以下代码时,出现错误“ Object required”。 I think the error is basically due to incorrect usage of decorators. 我认为该错误基本上是由于装饰器的使用不正确造成的。 Looking for help! 寻求帮助!

import seaborn as sns, numpy as np
import matplotlib.pyplot as plt
import xlwings as xw
import pandas as pd
from pandas import DataFrame



@xw.func
@xw.arg('df', pd.DataFrame, index = False, header=True)
@xw.arg('x_name', category = str)
@xw.arg('y_name', category = str)

def BOX_Plot(df,x_name,y_name):

    dt = pd.DataFrame(df)
    names = x_name
    bill =  y_name


    sns.set_style("whitegrid")
    ax = sns.boxplot(x=names, y=bill, data=dt)

    medians = dt.groupby([names])[bill].median().values
    median_labels = [str(np.round(s, 2)) for s in medians]

    pos = range(len(medians))
    for tick,label in zip(pos,ax.get_xticklabels()):
        ax.text(pos[tick], medians[tick], median_labels[tick], 
                horizontalalignment='center', size='x-small', color='w', weight='semibold')

    plt.show()

    return "Done!"

代码是完美的,我忘了在VBA工具中添加Xlwings参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM