径向环形热图

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

   1 """径向环形热图
   2 Restored/adapted from supplied screenshots [99, 100, 101, 102].
   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; from _utils.palette_maps import palette_cmap, palette_stops, contrast_text
   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 np.random.seed(6)
  18 data=np.array([np.random.uniform(5*i,5*(i+1),48) for i in range(12)])
  19 data+=np.random.normal(0,15,data.shape)
  20 colors=palette_stops('diverging',count=5)
  21 cmap=LinearSegmentedColormap.from_list('custom',colors,N=256)
  22 num_columns=data.shape[1];gap_angle=10
  23 width=2*np.pi/num_columns*(360-gap_angle)/360
  24 theta=np.arange(num_columns)*width
  25 vmin,vmax=data.min(),data.max()
  26 fig,ax=plt.subplots(figsize=(8,6),dpi=150,subplot_kw={'polar':True})
  27 for i,row in enumerate(data):
  28     height=2;radius=height*i+10
  29     for j,value in enumerate(row):
  30         ax.bar(theta[j],height,bottom=radius,width=width,color=cmap((value-vmin)/(vmax-vmin)),edgecolor='white',linewidth=.5,align='edge')
  31     ax.text(theta[-1]+width+np.radians(gap_angle/2),radius+height/2,str(i+1),ha='center',va='center',fontsize=6,rotation=-10)
  32 for angle,label in zip(theta+width/2,range(1,num_columns+1)):
  33     rotation=np.degrees(angle);flip=90<rotation<270
  34     ax.text(angle,radius+3,str(label),ha='right' if flip else 'left',va='center',rotation=rotation-180 if flip else rotation,rotation_mode='anchor',fontsize=8)
  35 ax.set(xticks=[],yticks=[],ylim=(0,radius+5));ax.spines['polar'].set_visible(False);ax.grid(False)
  36 cb=fig.colorbar(ScalarMappable(norm=Normalize(vmin,vmax),cmap=cmap),ax=ax,orientation='vertical',pad=.15,fraction=.05)
  37 cb.ax.tick_params(labelsize=8)
  38 ax.text(0,0,'径向热图',ha='center',va='center',fontsize=12,fontweight='bold',color='#c0627a')
  39 plt.tight_layout();plt.show()
  40