局部整体(七)利用python绘制圆形嵌套图
圆形嵌套图( Circular Packing)简介
将一组组圆形互相嵌套起来,以显示数据的层次关系,类似于矩形树图。数据集中每个实体都由一个圆表示,圆圈大小与其代表的值成正比,相对于treemap,圆堆图更直观简洁,虽然利用率上有缺陷。
快速绘制
-
基于circlify
import circlify import matplotlib.pyplot as plt # 自定义数据 data = [{'id': 'World', 'datum': 6964195249, 'children' : [ {'id' : "North America", 'datum': 450448697, 'children' : [ {'id' : "United States", 'datum' : 308865000}, {'id' : "Mexico", 'datum' : 107550697}, {'id' : "Canada", 'datum' : 34033000} ]}, {'id' : "South America", 'datum' : 278095425, 'children' : [ {'id' : "Brazil", 'datum' : 192612000}, {'id' : "Colombia", 'datum' : 45349000}, {'id' : "Argentina", 'datum' : 40134425} ]}, {'id' : "Europe", 'datum' : 209246682, 'children' : [ {'id' : "Germany", 'datum' : 81757600}, {'id' : "France", 'datum' : 65447374}, {'id' : "United Kingdom", 'datum' : 62041708} ]}, {'id' : "Africa", 'datum' : 311929000, 'children' : [ {'id' : "Nigeria", 'datum' : 154729000}, {'id' : "Ethiopia", 'datum' : 79221000}, {'id' : "Egypt", 'datum' : 77979000} ]}, {'id' : "Asia", 'datum' : 2745929500, 'children' : [ {'id' : "China", 'datum' : 1336335000}, {'id' : "India", 'datum' : 1178225000}, {'id' : "Indonesia", 'datum' : 231369500} ]} ]}] # 计算圆的位置 circles = circlify.circlify( data, show_enclosure=False, # 不展示最外层的圈 target_enclosure=circlify.Circle(x=0, y=0, r=1) ) # 初始化布局 fig, ax = plt.subplots(figsize=(8,8)) ax.axis('off') # 标题 ax.set_title('Repartition of the world population') # 轴范围设置 lim = max( max( abs(circle.x) + circle.r, abs(circle.y) + circle.r, ) for circle in circles ) plt.xlim(-lim, lim) plt.ylim(-lim, lim) # 绘制所有level=2的圆(各大洲) for circle in circles: if circle.level != 2: continue x, y, r = circle ax.add_patch( plt.Circle((x, y), r, alpha=0.5, linewidth=2, color="lightblue")) # 绘制level=3的圆(各大洲的各个国家),并标注国家名称 for circle in circles: if circle.level != 3: continue x, y, r = circle label = circle.ex["id"] ax.add_patch( plt.Circle((x, y), r, alpha=0.5, linewidth=2, color="#69b3a2")) plt.annotate(label, (x,y ), ha='center', color="white") # 为所有level=2的圆(各大洲)标注名称 for circle in circles: if circle.level != 2: continue x, y, r = circle label = circle.ex["id"] plt.annotate(label, (x,y ) ,va='center', ha='center', bbox=dict(facecolor='white', edgecolor='black', boxstyle='round', pad=.5))
总结
以上利用circlify
并结合matplotlib来绘制基本的圆形嵌套图。
共勉~