正负折叠地平线图
代码截图恢复与适配 · 来源与修改说明 · 下载完整代码
1 """正负折叠地平线图
2 Restored/adapted from supplied screenshots [68, 69, 70].
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 from scipy.interpolate import make_interp_spline
18 from matplotlib.patches import Patch
19 def create_data(x,size,n,max_value):
20 sigma=size/30
21 return max_value*np.exp(-.5*((x-n)/sigma)**2)
22 np.random.seed(3)
23 x=np.linspace(0,80,300)
24 y_list=[]
25 for i in range(20):
26 peaks=np.sort(np.random.uniform(0,80,size=200))
27 means=np.random.uniform(-.25,.3,200)
28 temp_y=sum(create_data(x,80,p,m) for p,m in zip(peaks,means))
29 y_list.append(temp_y)
30 fig,ax=plt.subplots(figsize=(10,6),dpi=150)
31 y_offset=.6
32 for i,y in enumerate(y_list):
33 x_smooth=np.linspace(x.min(),x.max(),500)
34 y_smooth=make_interp_spline(x,y)(x_smooth)
35 for sign,color in [(1,'#e98184'),(-1,'#81b7d9')]:
36 y_pos=np.maximum(sign*y_smooth,0)
37 for j in range(4):
38 y_plot=np.maximum(np.minimum(y_pos,y_offset*(j+1)),y_offset*j)
39 y_bottom=y_offset*i
40 y_top=y_plot-j*y_offset+y_offset*i
41 ax.fill_between(x_smooth,y_bottom,y_top,color=color,alpha=.5)
42 ax.plot(x_smooth,y_top,color='white',linewidth=.5)
43 ax.set(xlim=(0,70),ylim=(0,13))
44 ax.set_xticks([1.5,10,20,30,40,50,60,68.5],range(2020,2028),fontweight='bold',color='#81b7d9')
45 ax.set_yticks([.3+i*.6 for i in range(20)],[chr(i) for i in range(65,85)],fontweight='bold',color='#81b7d9')
46 ax.legend(handles=[Patch(color='#e98184',label='正向偏差'),Patch(color='#81b7d9',label='负向偏差')],loc='upper right',ncols=2,frameon=False)
47 ax.set_title('正负折叠地平线图',loc='left',color='#3680ae',fontweight='bold')
48 plt.tight_layout();plt.show()
49