双向峰形河流图
代码截图恢复与适配 · 来源与修改说明 · 下载完整代码
1 """双向峰形河流图
2 Restored/adapted from supplied screenshots [8, 88, 89, 90].
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 matplotlib.ticker as ticker
18 from matplotlib.colors import ListedColormap, BoundaryNorm
19 def generate_single_weighted_random(scale=1.5,lower=1,upper=10):
20 return np.clip(np.random.exponential(scale)+lower,lower,upper)
21 def create_smooth_peak_data(x,start,peak,end,max_value):
22 y=np.zeros_like(x)
23 rising=(x>=start)&(x<=peak);sigma_rise=(peak-start)/3
24 y[rising]=max_value*np.exp(-((x[rising]-peak)**2)/(2*sigma_rise**2))
25 falling=(x>peak)&(x<=end);sigma_fall=(end-peak)/3
26 y[falling]=max_value*np.exp(-((x[falling]-peak)**2)/(2*sigma_fall**2))
27 return y
28 hex_colors=['#214e81','#456991','#6983a2','#8d9eb2','#dc9fb0','#cf8b9e','#c2768b','#a55d75']
29 thresholds=[5,7.5,8,12,15,20,25]
30 def assign_color(value):return hex_colors[sum(value>t for t in thresholds)]
31 np.random.seed(30)
32 x=np.linspace(0,800,800)
33 y_list,color_list,categories=[],[],[]
34 def generate_data(num_categories,start_base,peak_base,end_base,interval,direction):
35 for i in range(num_categories):
36 offset=i*interval if direction=='forward' else -i*interval
37 max_value=generate_single_weighted_random(6,1,10000)
38 y_list.append(create_smooth_peak_data(x,start_base+offset,peak_base+offset,end_base+offset,max_value))
39 color_list.append(assign_color(max_value));categories.append(f'类别{len(categories)+1}')
40 generate_data(72,720,740,820,10,'backward');generate_data(72,0,20,100,10,'forward')
41 y_list=np.array(y_list)
42 fig,ax=plt.subplots(figsize=(10,5),dpi=150)
43 polys=ax.stackplot(x,y_list,colors=color_list,labels=categories,zorder=10,alpha=1,baseline='wiggle')
44 for poly in polys:
45 verts=poly.get_paths()[0].vertices
46 ax.plot(verts[:,0],verts[:,1],color='white',zorder=20,linewidth=.5)
47 # Colors are discrete peak-amplitude bins in the original; show matching bin boundaries.
48 cmap=ListedColormap(hex_colors);norm=BoundaryNorm([0,*thresholds,40],cmap.N)
49 cb=fig.colorbar(ScalarMappable(norm=norm,cmap=cmap),ax=ax,orientation='vertical',pad=.01,fraction=.05,extend='max')
50 cb.set_label('序列峰值分档');cb.ax.tick_params(size=0)
51 ax.grid(axis='x',which='major',linestyle='-',linewidth=1,color='white')
52 ax.xaxis.set_major_locator(ticker.MultipleLocator(100))
53 ax.set_xticks(range(0,801,100),range(2020,2029));ax.set(ylim=(-75,75),yticks=[])
54 ax.set_title('双向峰形河流图',loc='left')
55 plt.tight_layout();plt.show()
56