排名圆弧条形图
代码截图恢复与适配 · 来源与修改说明 · 下载完整代码
1 """排名圆弧条形图
2 Restored/adapted from supplied screenshots [64, 65, 66].
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 faker import Faker
18 Faker.seed(6);np.random.seed(6)
19 fake=Faker()
20 company_name=[fake.company() for _ in range(16)]
21 growth_data=np.sort(np.random.uniform(0,100,16))
22 def create_colors(hex_colors,data):
23 cmap=LinearSegmentedColormap.from_list('custom',hex_colors)
24 sm=ScalarMappable(norm=Normalize(min(data),max(data)),cmap=cmap)
25 return [sm.to_rgba(v)[:3] for v in data]
26 fig,ax=plt.subplots(figsize=(10,8),subplot_kw={'projection':'polar'},dpi=150)
27 max_value=max(growth_data)*2.75
28 colors=create_colors(['#214e81','#a55d75'],growth_data)
29 inner_radius=15
30 for i,(label,value) in enumerate(zip(company_name,growth_data)):
31 inner_radius+=1.7;ring_width=1.5
32 theta_start=0;theta_end=value/max_value*2*np.pi
33 ax.bar((theta_start+theta_end)/2,height=ring_width,width=theta_end-theta_start,bottom=inner_radius,color=colors[i],alpha=.85)
34 attr=dict(color=colors[i],rotation=np.degrees(theta_end)+5,ha='left') if theta_end<np.pi/2 else dict(color='white',rotation=np.degrees(theta_end-np.pi)-5,ha='left')
35 ax.text(theta_end,inner_radius+ring_width/2,f' {value:.1f}%',va='center',fontsize=8,fontweight='bold',rotation_mode='anchor',**attr)
36 ax.text(-.01,inner_radius+ring_width/2,label,ha='right',va='center',color=colors[i],fontsize=8,fontweight='bold')
37 ax.set(xticks=[],yticks=[],ylim=(0,inner_radius+3))
38 ax.grid(False);ax.spines['polar'].set_visible(False)
39 ax.set_theta_direction(1);ax.set_theta_offset(np.pi*1.5)
40 fig.text(.06,.91,'公司增长率排名',fontsize=24,fontweight='bold',color='#575864')
41 fig.text(.06,.86,'合成数据 · 共享角度尺度',fontsize=12,color='#575864')
42 fig.subplots_adjust(left=.12,right=.99,top=.9,bottom=.06)
43 plt.show()
44