同心环形柱状图
代码截图恢复与适配 · 来源与修改说明 · 下载完整代码
1 """同心环形柱状图
2 Restored/adapted from supplied screenshots [53, 54, 55].
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 matplotlib.patches import Patch
18 values=[11,12,12,14,15,20,22,22,24,24,26,27]
19 max_value=max(values)*1.1
20 num_rings=len(values)
21 categories=[f'类别{i+1}' for i in range(num_rings)]
22 fig,ax=plt.subplots(figsize=(8,5),subplot_kw={'projection':'polar'},dpi=150)
23 ax.set_theta_direction(-1);ax.set_theta_offset(np.pi/2)
24 inner_radius_offset=2
25 for i,(label,value) in enumerate(zip(categories,values)):
26 inner_radius=i+inner_radius_offset
27 ring_width=.8
28 theta_start=0;theta_end=value/max_value*2*np.pi
29 rotation=-np.degrees((theta_start+theta_end)/2) if np.degrees(theta_end)<180 else 180-np.degrees((theta_start+theta_end)/2)
30 color='#9dc1c5' if value<15 else '#d7a6b3' if value>25 else '#8e93af'
31 ax.bar(x=(theta_start+theta_end)/2,height=ring_width,width=theta_end-theta_start,bottom=inner_radius,color=color)
32 ax.text((theta_start+theta_end)/2,inner_radius+ring_width/2,f'{value}',ha='center',va='center',color='white',fontsize=6,fontweight='bold',rotation=rotation,rotation_mode='anchor')
33 handles=[Patch(color=c,label=l) for c,l in zip(['#9dc1c5','#8e93af','#d7a6b3'],['低值','中值','高值'])]
34 fig.legend(handles=handles,loc='center right',frameon=False)
35 ax.set_xticks([]);ax.set_yticks(np.arange(num_rings)+inner_radius_offset,categories,fontsize=6)
36 ax.set_rlabel_position(0)
37 ax.grid(axis='y',linestyle='-',linewidth=1,color='white')
38 ax.spines['polar'].set_visible(False)
39 fig.suptitle('环形柱状图',x=.02,ha='left')
40 plt.tight_layout();plt.show()
41