使用xlwings在Excel之外进行绘图。

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

我正在使用xlwings从Excel中调用一些Python代码。我想把一些结果绘制成一个散点图,我有下面的代码。

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D

    x = data['X']
    y = data['Y']
    z = data['Z']

    # Filter out elements that work
    z[z<1] = np.nan

    length, width = section_properties.shape

    fig = plt.figure()

#    # Create Map
    cm = plt.get_cmap("RdYlGn")
    col = np.arange(length)

#    Create 3D plot
    ax3D = fig.add_subplot(111, projection='3d')
    p3d = ax3D.scatter(x, y, z, c=col, marker='o') 
    ax3D.set_xlabel('X label')
    ax3D.set_ylabel('Y label')
    ax3D.set_zlabel('Z label')

#    Option 1: show on Excel (static)
    sht = xw.Book.caller().sheets['Results']
    sht.pictures.add(fig, name='MyPlot', update=True)

    # Option 2: show on its own window (interactive)
#   plt.show()

选项1很好用,可以把3D散点图放在Excel工作表上。唯一的问题是,这个图是静态的(即我不能旋转或放大或缩小)。我希望我放在选项2下的代码能在Excel之外创建一个我可以操作的图形,但它不起作用。

有没有办法在新的窗口上生成这样一个图?

谢谢。

matplotlib xlwings
1个回答
0
投票

如果有人遇到同样的问题,我通过用plotly生成一个HTML文件来解决,然后在浏览器中可视化。请看下面的代码。

    import plotly.graph_objects as go
    import plotly.io as pio

    pio.renderers.default = "browser"

    fig = go.Figure(data=[go.Scatter3d(
        x=x,
        y=y,
        z=z,
        mode='markers',
        marker=dict(
            size=12,
            color=z,                # set color to an array/list of desired values
            colorscale='Rainbow',   # choose a colorscale
            opacity=0.8
        )
    )])

    # tight layout
    fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
    fig.write_html('tmp.html', auto_open=True)

谢谢!

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