三维等高线

代码截图恢复与适配 · 来源与修改说明 · 下载完整代码

   1 """三维等高线
   2 Restored/adapted from supplied screenshots [40, 41].
   3 Source: 小明的代码美学 (as shown in supplied screenshots).
   4 This is a runnable restoration, not a byte-for-byte original source file.
   5 See SOURCE.md for missing inputs and documented corrections.
   6 """
   7 import numpy as np
   8 import pandas as pd
   9 import matplotlib.pyplot as plt
  10 from matplotlib.colors import LinearSegmentedColormap, Normalize, to_hex
  11 from matplotlib.cm import ScalarMappable
  12 from pathlib import Path
  13 # Missing .mplstyle files are replaced only by explicit, portable display defaults.
  14 plt.rcParams.update({'font.sans-serif':['Microsoft YaHei','DejaVu Sans'],
  15  'axes.unicode_minus':False,'figure.facecolor':'white','axes.facecolor':'white',
  16  'axes.spines.top':False,'axes.spines.right':False,'font.size':9})
  17 import plotly.graph_objects as go
  18 rows, cols = 32, 22
  19 x = np.linspace(-1, 1, cols)
  20 y = np.linspace(-1.7, 1.3, rows)
  21 X, Y = np.meshgrid(x, y)
  22 Z = np.exp(-((X+.5)**2+(Y+.5)**2)/.7)*1.5 + np.exp(-((X-.5)**2+(Y-.5)**2)/.3)
  23 colorscale_custom = [[0., '#2f648e'], [.5, '#e9d1ab'], [1., '#c3476a']]
  24 
  25 cmap=LinearSegmentedColormap.from_list('custom',[col for pos,col in colorscale_custom],N=256)
  26 levels=np.linspace(Z.min(),Z.max(),20)
  27 fig_contour=plt.figure()
  28 cs=plt.contour(X,Y,Z,levels=levels)
  29 plt.close(fig_contour)
  30 fig=go.Figure()
  31 for i,level in enumerate(cs.levels):
  32     for seg in cs.allsegs[i]:
  33         if len(seg)==0: continue
  34         color=to_hex(cmap((level-Z.min())/(Z.max()-Z.min())))
  35         fig.add_trace(go.Scatter3d(x=seg[:,0],y=seg[:,1],z=[level]*len(seg),mode='lines',line=dict(color=color,width=8),showlegend=False))
  36 fig.update_layout(scene=dict(xaxis_title='X',yaxis_title='Y',zaxis_title='Z'),margin=dict(l=0,r=0,t=0,b=0))
  37 # Export-safe frame leaves room for outer 3D ticks.
  38 fig.update_layout(margin=dict(l=30,r=30,t=30,b=35))
  39 fig.update_layout(scene_camera=dict(eye=dict(x=1.65,y=1.65,z=1.5)))
  40 fig.show()
  41