峰值标注堆叠面积图
代码截图恢复与适配 · 来源与修改说明 · 下载完整代码
1 """峰值标注堆叠面积图
2 Restored/adapted from supplied screenshots [17, 18, 19, 20, 21].
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 import random
19 from scipy.signal import find_peaks
20 read_custom_data = False
21 def create_data(x,size,n,max_value):
22 sigma = size/30
23 return max_value*np.exp(-.5*((x-n)/sigma)**2)
24 if read_custom_data:
25 data = pd.read_csv('data.csv')
26 else:
27 random.seed(16)
28 size,x_max = 300,80
29 x = np.linspace(0,x_max,size)
30 peaks = [5,15,23,38,35,48,53,68]
31 means = [2.5,1.2,3.,2.5,1.,1.5,2.,2.2]
32 data = {'x':x}
33 for i in range(4):
34 y=np.zeros_like(x)
35 for p,m in zip(peaks,means):
36 y += create_data(x,x_max,p,m*random.random())
37 data[f'类别{i+1}']=y
38 data=pd.DataFrame(data)
39 x=data['x'].values
40 categories=[c for c in data.columns if c!='x']
41 colors=['#e7c2cb','#daa2b0','#cd8295','#c0627a']
42 fig=go.Figure()
43 for cat,color in zip(categories,colors):
44 fig.add_trace(go.Scatter(x=x,y=data[cat],fill='tonexty',mode='none',name=cat,fillcolor=color,stackgroup='one'))
45 y_stack=np.cumsum(data[categories].T.values,axis=0)
46 for ys in y_stack:
47 fig.add_trace(go.Scatter(x=x,y=ys,mode='lines',line=dict(width=2,color='#ffffff'),showlegend=False))
48 idx,_=find_peaks(y_stack[-1])
49 fig.add_trace(go.Scatter(x=x[idx],y=y_stack[-1][idx],mode='markers',marker=dict(symbol='circle',size=8,color='#ffffff',line=dict(width=2,color='#c0627a')),showlegend=False))
50 for px,py in zip(x[idx],y_stack[-1][idx]):
51 fig.add_annotation(x=px,y=py+.3,text=f'{py:.2f}',showarrow=False)
52 fig.update_layout(xaxis=dict(title='X 轴',range=[0,70]),yaxis=dict(title='值',range=[0,10]),width=800,height=500,
53 legend=dict(orientation='h',y=1.08,x=.5,xanchor='center'))
54 # Match reference's white plot background; leave room for annotations.
55 fig.update_layout(margin=dict(l=30,r=30,t=30,b=35))
56 fig.update_layout(plot_bgcolor='white',paper_bgcolor='white',font=dict(color='#a65c70'),xaxis=dict(showgrid=False,showline=True,linecolor='#c99baa'),yaxis=dict(showgrid=False,showline=True,linecolor='#c99baa'))
57 fig.show()
58