【Python】Creating a wireframe in Plotly.

プログラミング

This article is available in: 日本語

This article is a reminder to create a wireframe in plotly.

Plotly is a library that makes it easy to create interactive graphs, allowing you to move the graphs around.

In plotly, I could not find a function to visualize wireframes like matplotlib’s plot_wireframe(), so I created one.

import numpy as np
import plotly.graph_objs as go
import plotly.io as pio


x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
xx, yy = np.meshgrid(x, y)
z = xx**2 - yy**2

def plot_wireframe(xx, yy, z, color='#0066FF', linewidth=1):
    line_marker = dict(color=color, width=linewidth)
    lines = []
    for i, j, k in zip(xx, yy, z):
        lines.append(go.Scatter3d(x=i, y=j, z=k, mode='lines', line=line_marker))
        lines.append(go.Scatter3d(x=j, y=i, z=-k, mode='lines', line=line_marker))
        
    layout = go.Layout(showlegend=False)
    return go.Figure(data=lines, layout=layout)


fig = plot_wireframe(xx, yy, z)
fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
fig.show()
# pio.write_html(fig, 'plotly-wireframe.html', include_plotlyjs='cdn', full_html=False)

bonus

Wireframe visualization in matplotlib

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns

sns.set(style='whitegrid')
%config InlineBackend.figure_formats = ['svg']
 

x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
xx, yy = np.meshgrid(x, y)
z = xx**2 - yy**2
 

ax = Axes3D(plt.figure())
ax.plot_wireframe(xx, yy, z, linewidth=1)
# plt.savefig('fig.svg')
plt.show()
タイトルとURLをコピーしました