南丁格尔玫瑰图

代码截图恢复与适配 · 来源与修改说明 · 下载完整代码

   1 """南丁格尔玫瑰图
   2 Restored/adapted from supplied screenshots [57, 58].
   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 values=np.array([30,35,40,45,50,55,60,65,70])
  18 labels=[f'类别{i+1}' for i in range(len(values))]
  19 width=2*np.pi*values/sum(values)
  20 colors=['#dc9eb5','#e3d0d7','#b0a3c0']*3
  21 fig,ax=plt.subplots(subplot_kw={'projection':'polar'},figsize=(8,5),dpi=150)
  22 start_x=0
  23 for i,value in enumerate(values):
  24     start_x+=.5*width[i]
  25     ax.bar(start_x,value,width=width[i],bottom=10.,linewidth=2,edgecolor='white',color=colors[i])
  26     # Correct the screenshot's percentage formula (width / 2pi, not width / pi).
  27     label=f'{labels[i]}\n{value/values.sum()*100:.1f}% | {value}'
  28     offset=[12,-4,0,0,0,0,0,0,0][i]
  29     ax.text(start_x,value*.75+10+offset,label,color='white',fontsize=7,ha='center',va='center',fontweight='bold',
  30             bbox=dict(facecolor='#75879655',edgecolor='none',boxstyle='round,pad=.5'))
  31     start_x+=.5*width[i]
  32 ax.set(xticks=[],yticks=[],ylim=(0,85))
  33 ax.spines['polar'].set_visible(False)
  34 ax.set_theta_direction(1);ax.set_theta_offset(np.pi*.5)
  35 fig.text(.18,.5,'南丁格尔\n玫瑰图',fontsize=24,ha='center',va='center',fontweight='bold',color='#515a85')
  36 fig.subplots_adjust(left=.32,right=.98,top=.98,bottom=.02)
  37 plt.show()
  38