三维分层面积图

部分代码恢复,缺失段按图补全 · 来源与修改说明 · 下载完整代码

   1 """三维分层面积图
   2 Restored/adapted from supplied screenshots [7].
   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 # Only CSV-reader code page 007 was supplied; plotting section reconstructed from 009.
  18 import csv
  19 from matplotlib.collections import PolyCollection
  20 from scipy.interpolate import make_interp_spline
  21 def polygon_under_graph(x,y):
  22     return [(x[0],0.),*zip(x,y),(x[-1],0.)]
  23 def read_csv(csv_path):
  24     categories=[];x_vals=[];y_cols=None
  25     with open(csv_path,'r',newline='',encoding='utf-8') as f:
  26         reader=csv.reader(f);header=next(reader);categories=header[1:]
  27         y_cols=[[] for _ in categories]
  28         for row in reader:
  29             if not row:continue
  30             x_vals.append(float(row[0]))
  31             for i in range(len(categories)):y_cols[i].append(float(row[i+1]))
  32     return np.array(x_vals,dtype=float),categories,[np.array(col,dtype=float) for col in y_cols]
  33 read_custom_data=False
  34 if read_custom_data:
  35     x,categories,y_list=read_csv('data.csv')
  36 else:
  37     x=np.arange(1,13)
  38     categories=[f'Scenario {i+1}' for i in range(6)]
  39     y_list=[np.array(v) for v in [
  40       [1000,1006,1009,1005,995,980,964,965,1000,1020,1040,1000],
  41       [995,1006,1000,985,976,975,966,1002,1015,1025,1030,970],
  42       [990,1003,1008,1002,981,970,975,990,1010,1040,1000,1050],
  43       [998,1003,1012,1009,991,982,980,982,990,1004,1035,1026],
  44       [1000,1003,1005,1007,1000,994,990,995,1024,1033,1028,1034],
  45       [1014,1015,1020,1024,1020,1004,994,992,1050,992,1054,1000]]]
  46 BASE=900
  47 colors=['#dc6bc8','#f19a42','#f1d63e','#40cb6b','#398dd7','#7f61cc']
  48 fig=plt.figure(figsize=(8,7),dpi=150);ax=fig.add_subplot(projection='3d')
  49 x_smooth=np.linspace(x.min(),x.max(),300)
  50 for i,(values,color) in enumerate(zip(y_list,colors)):
  51     y_smooth=make_interp_spline(x,values)(x_smooth)
  52     vertices=[(x_smooth[0],BASE),*zip(x_smooth,y_smooth),(x_smooth[-1],BASE)]
  53     poly=PolyCollection([vertices],facecolors=color,alpha=.32,edgecolors='none')
  54     ax.add_collection3d(poly,zs=i+1,zdir='y')
  55     ax.plot(x_smooth,np.full(len(x_smooth),i+1),y_smooth,color=color,linewidth=2.5)
  56 ax.set(xlim=(x.min(),x.max()),ylim=(1,6),zlim=(BASE,1080),xlabel='Month',ylabel='Scenario',zlabel='Water level (m)')
  57 ax.set_yticks(range(1,7));ax.view_init(elev=25,azim=-75)
  58 ax.set_box_aspect((1.25,1.5,1))
  59 for axis in [ax.xaxis,ax.yaxis,ax.zaxis]:
  60     axis.pane.fill=False;axis._axinfo['grid'].update(linestyle='--',color='#999999')
  61 plt.tight_layout();plt.show()
  62