前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >超实用,百行Python代码制作动态树地图

超实用,百行Python代码制作动态树地图

作者头像
lyhue1991
发布2021-07-16 15:26:22
7390
发布2021-07-16 15:26:22
举报
文章被收录于专栏:Python与算法之美

今日表情?

树地图(tree map)是一种适用于显示大量分层结构的数据,它是饼状图的一种高维度替代者,可以用面积直观显示各个部分的占比。

先上图片:

再上视频:

最后上代码:

代码语言:javascript
复制
import numpy as np 
import pandas as pd 
from matplotlib import pyplot as plt
import matplotlib.animation as  animation 

import imageio
import os 
import cv2
from PIL import Image
import squarify


cmap = [
'#2E91E5',
'#1CA71C',
'#DA16FF',
'#B68100',
'#EB663B',
'#00A08B',
'#FC0080',
'#6C7C32',
'#862A16',
'#620042',
'#DA60CA',
'#0D2A63']*100

plt.rcParams['animation.writer'] = 'html'
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def html_to_gif(html_file, gif_file, duration=0.1):
    path = html_file.replace(".html","_frames")
    images = [os.path.join(path,x) for x in sorted(os.listdir(path))]
    frames = [imageio.imread(x) for x in images]
    imageio.mimsave(gif_file, frames, 'gif', duration=duration)
    return gif_file


df = pd.read_csv('./data/gdp_china_1993_2019.csv')
df["date"] = [str(x) for x in df["date"]]
df = df.set_index("date")
df.columns = [x if "自治区" not in x else x[0:2] for x in df.columns]
df = df.sort_values("2019",axis = 1,ascending=False)

figsize = (8,6)
dpi = 160
title = "中国大陆各省份历年GDP"
n_visible = 31 

def treemap_dance(df,filename = None,
    title = "中国大陆各省份历年GDP",figsize = (8,6),dpi = 120,duration = 2,n_visible= 31):
    
    assert filename is None or filename.endswith(".html"), "filename should like *.html!"
    
    fig,ax = plt.subplots(figsize=figsize,dpi=dpi)
    

    # 调整spines
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_visible(False)
    ax.spines["bottom"].set_visible(False)

    def plot_frame(i):
        
        ax.clear() 
        date = df.index[i]
        dfdata = pd.DataFrame(df.loc[date,:])
        dfdata.columns = ["values"]
        dfdata["color"] = [cmap[i] for i in range(len(dfdata))] 
        dfdata = dfdata.sort_values("values",ascending = True) 

        dfused = dfdata.iloc[n_visible::-1,:] 
        xdata = dfused.index.tolist()
        ydata = dfused["values"].tolist()
        colors = dfused["color"].tolist()

        #plt.rc('font', size=7,color = "white")
        squarify.plot(sizes = ydata, # 指定绘图数据
             label = xdata, # 指定标签
             color = colors, # 指定自定义颜色
             alpha = 0.5, # 指定透明度
             value = ydata, # 添加数值标签
             edgecolor = 'white', # 设置边界框为白色
             linewidth =3, # 设置边框宽度为3
             ax = ax,
             text_kwargs = {"size":8,"color":"black"},
             zorder = 0
        )

        #辅助设置
        ax.set_title(title,color = "black",fontsize = 12)
        ax.text(0.08, 0.92, str(date), va="center", ha="center",
                alpha=1.0, color ="white", size = 20,transform = ax.transAxes)
        plt.axis('off')
        plt.tick_params(top = 'off', right = 'off')
        

    my_animation = animation.FuncAnimation(fig,plot_frame,frames = range(0,len(df)),interval = int(duration*1000))
    if filename is None:
        try:
            from IPython.display import HTML
            HTML(my_animation.to_jshtml())
            return HTML(my_animation.to_jshtml())
        except ImportError:
            pass
    else:
        my_animation.save(filename)
        return filename

treemap_dance(df)

html_file = "treemap_dance.html"
gif_file = "treemap_dance.gif"
treemap_dance(df, filename = html_file)

html_to_gif(html_file,gif_file,duration=1.0)

主要原理是安装并使用了squarify 库来绘制树地图,并借助 matplotlib中的 animation制作动态图。

收工。?

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-06-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 算法美食屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
图数据库 KonisGraph
图数据库 KonisGraph(TencentDB for KonisGraph)是一种云端图数据库服务,基于腾讯在海量图数据上的实践经验,提供一站式海量图数据存储、管理、实时查询、计算、可视化分析能力;KonisGraph 支持属性图模型和 TinkerPop Gremlin 查询语言,能够帮助用户快速完成对图数据的建模、查询和可视化分析。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档