def test_treemap_options(fake_writer): c = TreeMap().add("演示数据", example_data, width="90%", height="100%", roam=False) c.render() _, content = fake_writer.call_args[0] assert_in("width", content) assert_in("height", content) assert_in("roam", content)
def test_treemap_base(fake_writer): data = [ {"value": 40, "name": "我是A"}, { "value": 180, "name": "我是B", "children": [ { "value": 76, "name": "我是B.children", "children": [ {"value": 12, "name": "我是B.children.a"}, {"value": 28, "name": "我是B.children.b"}, {"value": 20, "name": "我是B.children.c"}, {"value": 16, "name": "我是B.children.d"}, ], } ], }, ] c = TreeMap().add("演示数据", data) c.render() _, content = fake_writer.call_args[0] eq_(c.theme, "white") eq_(c.renderer, "canvas")
def draw_tree_picture(data, to_file, svg_name, colors=None): c = TreeMap(init_opts=opts.InitOpts(width="800px", height="600px", bg_color='white')) \ .add("", data) \ .set_global_opts(legend_opts=opts.LegendOpts(is_show=False), ) \ .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}", position='top')) c.render(to_file) to_svg(to_file, svg_name)
def test_treemap_base(): data = [ {"value": 40, "name": "我是A"}, { "value": 180, "name": "我是B", "children": [ { "value": 76, "name": "我是B.children", "children": [ {"value": 12, "name": "我是B.children.a"}, {"value": 28, "name": "我是B.children.b"}, {"value": 20, "name": "我是B.children.c"}, {"value": 16, "name": "我是B.children.d"}, ], } ], }, ] c = TreeMap().add("演示数据", data) assert c.theme == "white" assert c.renderer == "canvas" c.render("render.html")
def test_treemap_levels_options(fake_writer): c = TreeMap().add( "演示数据", example_data, width="90%", height="100%", roam=False, levels=opts.TreeMapLevelsOpts(), ) c.render() _, content = fake_writer.call_args[0] assert_in("levels", content)
def create_type_likes(df): # 分组求和 likes_type_message = df.groupby(['category']) likes_type_com = likes_type_message['likes'].agg(['sum']) likes_type_com.reset_index(inplace=True) # 处理数据 dom = [] for name, num in zip(likes_type_com['category'], likes_type_com['sum']): data = {} data['name'] = name data['value'] = num dom.append(data) print(dom) # 初始化配置 treemap = TreeMap(init_opts=opts.InitOpts(width="800px", height="400px")) # 添加数据 treemap.add('', dom) # 设置全局配置项,标题、工具箱(下载图片) treemap.set_global_opts(title_opts=opts.TitleOpts(title="各类型抖音大V点赞数汇总图", pos_left="center", pos_top="5"), toolbox_opts=opts.ToolboxOpts( is_show=True, feature={"saveAsImage": {}}), legend_opts=opts.LegendOpts(is_show=False)) treemap.render("各类型抖音大V点赞数汇总图.html")
def treemap_base() -> TreeMap: data = [ {"value": 40, "name": "我是A"}, { "value": 180, "name": "我是B", "children": [ { "value": 76, "name": "我是B.children", "children": [ {"value": 12, "name": "我是B.children.a"}, {"value": 28, "name": "我是B.children.b"}, {"value": 20, "name": "我是B.children.c"}, {"value": 16, "name": "我是B.children.d"}, ], } ], }, ] c = ( TreeMap() .add("演示数据", data) .set_global_opts(title_opts=opts.TitleOpts(title="TreeMap-基本示例")) ) return c
def treemap_official(): with open(os.path.join("fixtures", "treemap.json"), "r", encoding="utf-8") as f: data = json.load(f) c = (TreeMap().add( "演示数据", data).set_global_opts(title_opts=opts.TitleOpts(title="TreeMap-官方示例"))) return c
def test_treemap_options(fake_writer): data = [ { "value": 40, "name": "我是A" }, { "value": 180, "name": "我是B", "children": [{ "value": 76, "name": "我是B.children", "children": [ { "value": 12, "name": "我是B.children.a" }, { "value": 28, "name": "我是B.children.b" }, { "value": 20, "name": "我是B.children.c" }, { "value": 16, "name": "我是B.children.d" }, ], }], }, ] c = TreeMap().add("演示数据", data, width="90%", height="100%", roam=False) c.render() _, content = fake_writer.call_args[0] assert_in("width", content) assert_in("height", content) assert_in("roam", content)
def test_treemap_base(): data = [ { "value": 40, "name": "我是A" }, { "value": 180, "name": "我是B", "children": [{ "value": 76, "name": "我是B.children", "children": [ { "value": 12, "name": "我是B.children.a" }, { "value": 28, "name": "我是B.children.b" }, { "value": 20, "name": "我是B.children.c" }, { "value": 16, "name": "我是B.children.d" }, ], }], }, ] c = TreeMap().add("演示数据", data) eq_(c.theme, "white") eq_(c.renderer, "canvas") c.render()
def to_treemap(data, proj, version): complexity = {'name': f'{proj}-{version}', 'children': []} extract(complexity, 'complexity', data) maintainability = {'name': f'{proj}-{version}', 'children': []} extract(maintainability, 'maintainability', data) testability = {'name': f'{proj}-{version}', 'children': []} extract(testability, 'testability', data) readability = {'name': f'{proj}-{version}', 'children': []} extract(readability, 'readability', data) reusability = {'name': f'{proj}-{version}', 'children': []} extract(reusability, 'reusability', data) inheritance = {'name': f'{proj}-{version}', 'children': []} extract(inheritance, 'inheritance', data) treemap = TreeMap() for indicator in [ 'complexity', 'maintainability', 'testability', 'readability', 'reusability', 'inheritance' ]: treemap = treemap.add(series_name=indicator, data=[locals()[indicator]], leaf_depth=2, roam=False, label_opts=opts.LabelOpts(position='inside')) treemap = (treemap.set_global_opts( tooltip_opts=opts.TooltipOpts(formatter='{b}<br/>{a}: {c}'), toolbox_opts=opts.ToolboxOpts(feature=opts.ToolBoxFeatureOpts( magic_type=opts.ToolBoxFeatureMagicTypeOpts(is_show=False), data_zoom=opts.ToolBoxFeatureDataZoomOpts(is_show=False), brush=opts.ToolBoxFeatureBrushOpts(type_='clear'))), legend_opts=opts.LegendOpts(is_show=True, selected_mode='single', pos_top='7%', orient='horizontal', padding=0), title_opts=opts.TitleOpts( title=f'Code Quality Treemap of {proj}-{version}', pos_left='center'))) grid = Grid() grid.add(treemap, grid_opts=opts.GridOpts(pos_top='100%')) return grid
def paint_treemap(): data = get.get_treemap_data(get.get_today()) charts = (TreeMap(init_opts=opts.InitOpts(width="80%", height="400%")).add( "world", data=data["children"], label_opts=opts.LabelOpts(position="inside"), ).set_global_opts( legend_opts=opts.LegendOpts(is_show=True), title_opts=opts.TitleOpts(title="世界累计确诊分布", pos_left="leafDepth"), )) return charts
def pyechart_Tree_plot(self, filedata, para): from pyecharts.charts import Tree, TreeMap file_name = '树图.html' path_plotly = self.path_dir_plotly_html + os.sep + file_name # 文件路径,前面是文件夹后面是文件名 costumeTheme = self.themedict[para['theme']] costomSymbol = self.symboldict[para['Tsymbol']] # ----------------------------------------------------------------------- #df = pd.read_excel(r"E:\5-程序设计\A-编程语言\01Python\自定义\Pyecharts\组合\template\树.xlsx", sheet_name='Sheet1') df = pd.read_excel(filedata, sheet_name='Sheet1') dic = self.Tree_dict(df) print(dic) if para['Tstate'][0]: Tr = ( # 数据特点:可以没有value值 Tree( init_opts=opts.InitOpts(theme=costumeTheme, renderer="canvs", width=para['width'], height=para['height']) ).add( "", dic, layout=para['Tlayout'], collapse_interval=2, orient="LR", symbol=costomSymbol, symbol_size=para['Tsymbol_size'], # label_opts=opts.LabelOpts(is_show=True, color=para["color"], position="top", # font_size=para["font_size"], # font_family=para["font_family"]) )) chart = Tr elif para['Tstate'][1]: c = ( TreeMap(init_opts=opts.InitOpts( theme=costumeTheme, renderer="canvs", width=para['width'], height=para['height'])).add( series_name="演示数据", data=dic, leaf_depth=para['leaf_depth'], #节点深度,开启下钻,不完全显示 )) chart = c # add() missing 2 required positional arguments: 'series_name' and 'data' self.Common_code(chart, path_plotly, para) return path_plotly # 返回该HTML文件路径
def create_type_fans(df): dom = [] fans_type_message = df.groupby(['category']) fans_type_com = fans_type_message['fans'].agg(['sum']) fans_type_com.reset_index(inplace=True) for name, num in zip(fans_type_com['category'], fans_type_com['sum']): data = {} data['name'] = name data['value'] = num dom.append(data) print(dom) treemap = TreeMap(init_opts=opts.InitOpts(width="800px", height="400px")) treemap.add('', dom) treemap.set_global_opts(title_opts=opts.TitleOpts(title="各类型抖音大V粉丝数汇总图", pos_left="center", pos_top="5"), toolbox_opts=opts.ToolboxOpts( is_show=True, feature={"saveAsImage": {}}), legend_opts=opts.LegendOpts(is_show=False)) treemap.set_series_opts(treemapbreadcrumb_opts=opts.TreeMapBreadcrumbOpts( is_show=False)) treemap.render("各类型抖音大V粉丝数汇总图.html")
def treemap(d, series_name): c = ( TreeMap() .add(series_name, d) .set_series_opts( label_opts=opts.LabelOpts(position="inside", font_size=11, font_weight='lighter', formatter='{b}\n{c}' ), ) .set_global_opts(toolbox_opts=opts.ToolboxOpts(is_show=True), legend_opts=opts.LegendOpts(is_show=False), ) ) return c
def make_star_treemap(self): """ 根据演员参演电影数生成矩形树图 :return: """ # print(get_current_time() + '|-------> 正在生成 演员参演电影数 图表...') # 导入数据并初始化 csv_path = os.path.abspath(os.path.join(os.path.dirname("__file__"), os.path.pardir, "moviespider", "movie_info_top500.csv")) rows = pd.read_csv(csv_path, encoding='utf-8', dtype=str) # rows = pd.read_csv('../comments/movie_info_top500.csv', encoding='utf-8', dtype=str) to_drop = ['名称', '导演', '年份', '国别', '类型', '语言', '评分', '评分人数', '五星占比', '四星占比', '三星占比', '二星占比', '一星占比', '短评数', '简介'] res = rows.drop(to_drop, axis=1) # 数据分割 all_star_list = [] for i in res.itertuples(): # print(i[1] + '\n') for j in i[1].split(','): all_star_list.append(j) # 数据统计 df = pd.DataFrame(all_star_list, columns=['演员']) res = df.groupby('演员')['演员'].count().sort_values(ascending=False) all_star_list = [] for i in res.items(): if i[1] > 4: all_star_list.append({"value": i[1], "name": i[0]}) # 生成图标 c = TreeMap() c.add("参演电影数", all_star_list) c.set_global_opts(title_opts=opts.TitleOpts(title="电影TOP500榜单中 - 演员参演电影数", subtitle="至少参演5部影评以上")) htmlPath = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "analyse_data", "演员参演电影数.html")) pngPath = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "analyse_data", "演员参演电影数.png")) # 生成html c.render(htmlPath) # 生成png # make_snapshot(snapshot, c.render(), pngPath) # print(get_current_time() + '|-------> 已生成 演员参演电影数 图表...') return c
def show_genres(): data=select_data() # 矩形树图初始化 treemap = TreeMap(init_opts=opts.InitOpts(page_title="豆瓣电影-电影类型分布")) # 添加数据 treemap.add( series_name='电影类型', data=data, # 标签居中 label_opts=opts.LabelOpts(font_size=15, position="inside"), ) # 全局配置 treemap.set_global_opts( # 标题 title_opts=opts.TitleOpts( title="豆瓣电影-电影类型分布", pos_left='center' ), # 标签隐藏 legend_opts=opts.LegendOpts(is_show=False) ) # 生成HTML html="pages/iframes/genres.html" treemap.render("./templates/"+html) return html
label_opts=opts.LabelOpts(formatter="{b}: {c}", font_size=16), ).render('热搜词饼图.html')) resou_word_love = resou_word_love.sort_values('count', ascending=False).reset_index() words = [(resou_word_love['word'][i], resou_word_love['num'][i]) for i in range(resou_word_love.shape[0])] pie = (Pie(init_opts=opts.InitOpts(theme=ThemeType.CHALK)).add( "", words).set_global_opts( title_opts=opts.TitleOpts(title="微博婚恋类词语出现次数", pos_left='center'), legend_opts=opts.LegendOpts(is_show=False)).set_series_opts( label_opts=opts.LabelOpts(formatter="{b}: {c}", font_size=16), ).render('婚恋类热搜词饼图.html')) resou_word_person = resou_word_person.sort_values( 'num', ascending=False).reset_index() words = [{ '"value": {}, "name": {}"'.format(str(resou_word_person['num'][i]), resou_word_person['name'][i]) } for i in range(resou_word_person.shape[0])] tree = (TreeMap(init_opts=opts.InitOpts(theme=ThemeType.ESSOS)).add( "", words, pos_left=0, pos_right=0, pos_top=50, pos_bottom=50).set_global_opts( title_opts=opts.TitleOpts(title="热搜明星出现次数排名", pos_left='center'), legend_opts=opts.LegendOpts(is_show=False)).set_series_opts( label_opts=opts.LabelOpts(formatter="{b}\n\n {c}", font_size=17, color='black', position='inside', font_weight='bolder')).render('排序.html'))
import json from pyecharts import options as opts from pyecharts.charts import TreeMap with open("treemap.json", "r", encoding="utf-8") as f: data = json.load(f) c = (TreeMap().add( series_name="演示数据", data=data, levels=[ opts.TreeMapLevelsOpts( treemap_itemstyle_opts=opts.TreeMapItemStyleOpts( border_color="#555", border_width=4, gap_width=4)), opts.TreeMapLevelsOpts( color_saturation=[0.3, 0.6], treemap_itemstyle_opts=opts.TreeMapItemStyleOpts( border_color_saturation=0.7, gap_width=2, border_width=2), ), opts.TreeMapLevelsOpts( color_saturation=[0.3, 0.5], treemap_itemstyle_opts=opts.TreeMapItemStyleOpts( border_color_saturation=0.6, gap_width=1), ), opts.TreeMapLevelsOpts(color_saturation=[0.3, 0.5]), ], ).set_global_opts(title_opts=opts.TitleOpts( title="TreeMap-Levels-配置")).render("Treemap_levels.html"))
from pyecharts import options as opts from pyecharts.charts import TreeMap data = [ {"value": 40, "name": "我是A"}, { "value": 180, "name": "我是B", "children": [ { "value": 76, "name": "我是B.children", "children": [ {"value": 12, "name": "我是B.children.a"}, {"value": 28, "name": "我是B.children.b"}, {"value": 20, "name": "我是B.children.c"}, {"value": 16, "name": "我是B.children.d"}, ], } ], }, ] c = ( TreeMap() .add("演示数据", data) .set_global_opts(title_opts=opts.TitleOpts(title="TreeMap-基本示例")) .render("Treemap_base.html") )
def treeMapChart(df): type_of_plot = st.selectbox("Select Type of Plot",["TreeMap1 Multi-level","TreeMap2"]) # allc = list(df.columns[:20]) # allc # tmap = px.treemap(df,path=[allc, "Enfants de 0 à 14 ans", "CJE"], values= "Population 2016") # return tmap all_columns = df.columns treemap = TreeMap() if type_of_plot == "TreeMap1 Multi-level": columns_to_plot = st.selectbox("Select 1 column",all_columns,key='a' ) columns_to_plot1 = st.selectbox("Select 2 column",[col for col in df.columns if col not in [columns_to_plot]], key='b' ) # columns_to_plot2 = st.selectbox("Select 3 column",[col for col in df.columns if col not in [columns_to_plot, columns_to_plot1]], key='c' ) names = list(df[columns_to_plot]) def get_all_values(d): if isinstance(d, dict): for v in d.values(): yield from get_all_values(v) elif isinstance(d, list): for v in d: yield from get_all_values(v) else: yield d dictionaryObject = df.to_dict(); # print(list(get_all_values(dictionaryObject))) df2 = df.copy() df3 = df.drop('CJE', axis=1) df3.values.tolist() values_market = df3.values.tolist() df2 = df.copy() # print(values_market) childs = [] for j,indu_one in enumerate(names): data_now = df2[df2[columns_to_plot]==indu_one] data_1 = list(data_now[columns_to_plot]) # print(data_now.values.tolist()) child = [] child.extend({'name':data_1[i],'value':list(data_now[columns_to_plot])[i]} for i in range(0,len(data_now[columns_to_plot]))) childs.append(child) data_n = [{ 'name':i,'value':j, 'children': m} for i,j,m in zip(names,values_market,childs)] treemap.add(series_name="option",data=data_n,visual_min=300,leaf_depth=1, label_opts=opts.LabelOpts(position="inside"),) return treemap if type_of_plot == "TreeMap2": columns_to_plot = st.selectbox("Select 1 column",all_columns,key='a' ) columns_to_plot1 = st.selectbox("Select 1 column",[col for col in df.columns if col not in [columns_to_plot]], key='b' ) names = list(df[columns_to_plot]) values_market = list(df[columns_to_plot1]) df2 = df.copy() childs = [] data_n = [{'name':i, 'value':j,'value1':j} for i,j in zip(names,values_market)] # treemap = TreeMap(init_opts=opts.InitOpts(height='1080px',width='1920px')) treemap.add( series_name=columns_to_plot1, data=data_n, leaf_depth=2, node_click="zoomToNode", zoom_to_node_ratio=0.5*0.5, levels=[ opts.TreeMapLevelsOpts( #color_mapping_by='value', upper_label_opts= opts.LabelOpts(position="inside") , treemap_itemstyle_opts=opts.TreeMapItemStyleOpts( border_color="#555", border_width=4, gap_width=4 ) ), opts.TreeMapLevelsOpts( upper_label_opts= opts.LabelOpts(position="inside"), color_saturation=[0.3, 0.6], treemap_itemstyle_opts=opts.TreeMapItemStyleOpts( border_color_saturation=0.7, gap_width=2, border_width=2 ), ), # opts.TreeMapLevelsOpts( # color_saturation=[0.3, 0.5], # treemap_itemstyle_opts=opts.TreeMapItemStyleOpts( # border_color_saturation=0.6, gap_width=1 # ), # ), # opts.TreeMapLevelsOpts(color_saturation=[0.3, 0.5]), ], ) treemap.set_series_opts(label_opts=opts.LabelOpts( is_show = True, position = 'inside',# position 'top','left','right','bottom','inside','insideLeft','insideRight'..... font_size = 20, # color color= '#ffffff', # font_style 'normal','italic','oblique' font_style = 'nomal' , # font_weight 'normal','bold','bolder','lighter' font_weight = None, # font_family 'Arial', 'Courier New', 'Microsoft YaHei' .... font_family = 'Microsoft YaHei', # rotate -90 90 rotate = '0', # margin margin = 20, interval = None, # horizontal_align 'left','center','right' horizontal_align = 'center', # vertical_align :'top','middle','bottom' vertical_align = None, ) ) treemap.set_global_opts(toolbox_opts=opts.ToolboxOpts(pos_left='8%'), title_opts=opts.TitleOpts(title="TreeMap")) return treemap
data = [ {"value": 40, "name": "我是A"}, { "value": 180, "name": "我是B", "children": [ { "value": 76, "name": "我是B.children", "children": [ {"value": 12, "name": "我是B.children.a"}, {"value": 28, "name": "我是B.children.b"}, {"value": 20, "name": "我是B.children.c"}, {"value": 16, "name": "我是B.children.d"}, ], } ], }, ] c = ( TreeMap() .add("演示数据", data) .set_global_opts(title_opts=opts.TitleOpts(title="TreeMap-基本示例")) ) c.width = "100%" put_html(c.render_notebook())
'value': '1', 'name': '人力资源管理' }] }, ] treemap = ( TreeMap().add( '各专业体育检测抽样人数', data, pos_left='center', # 主图的位置 tooltip_opts=opts.TooltipOpts(is_show=True), # 子标签展示,大小,字体 label_opts=opts.LabelOpts(is_show=True, font_size=14, font_family='serif', vertical_align='top')). set_global_opts( title_opts=opts.TitleOpts(title='矩形树图\n'), # 图左上角:标题 legend_opts=opts.LegendOpts(is_show=True), # 图上面中间:图例 toolbox_opts=opts.ToolboxOpts(is_show=True), # 图右上角:工具箱 # tooltip_opts=opts.TooltipOpts(is_show=True), # 图上:提示框 # visualmap_opts=opts.VisualMapOpts(is_show=True), # 图右下角:视觉映射 )) # 图的宽高 treemap.width = '1000px' treemap.height = '600px' # 保存为html文件 treemap.render('./data/treemap.html')
if base_path != "": path = base_path + "." + key else: path = key if re.match(r"/^\$/", key): pass else: child = {"name": path, "children": []} target["children"].append(child) if isinstance(source[key], dict): convert(source[key], child, path) else: target["value"] = source["$count"] convert(source=data, target=tree_map_data, base_path="") (TreeMap(init_opts=opts.InitOpts(width="1200px", height="720px")).add( series_name="option", data=tree_map_data["children"], visual_min=300, leaf_depth=1, # 标签居中为 position = "inside" label_opts=opts.LabelOpts(position="inside"), ).set_global_opts( legend_opts=opts.LegendOpts(is_show=False), title_opts=opts.TitleOpts(title="Echarts 配置项查询分布", subtitle="2016/04", pos_left="leafDepth"), ).render("echarts_option_query.html"))
import json from pyecharts.charts import TreeMap import pyecharts.options as opts with open('GDP_data_1.json', 'r', encoding='utf-8') as f: j = json.load(f) data = [j] map = TreeMap(init_opts=opts.InitOpts(width='1200px', height='800px')) map.add( '', data, label_opts=opts.LabelOpts(position='inside'), ) map.render('map.html')
def plot_tree(self, depth=3): data = self.describe_tree(self.tree) tree_map = TreeMap() tree_map.add(self.name, data, leaf_depth=depth, width=800, height=600) tree_map.render() return tree_map
"name": "我是B", "children": [{ "value": 76, "name": "我是B.children", "children": [ { "value": 12, "name": "我是B.children.a" }, { "value": 28, "name": "我是B.children.b" }, { "value": 20, "name": "我是B.children.c" }, { "value": 16, "name": "我是B.children.d" }, ], }], }, ] maptree = TreeMap() maptree.add("", data).render_notebook()
def test_treemap_base(fake_writer): c = TreeMap().add("演示数据", example_data) c.render() _, content = fake_writer.call_args[0] assert_equal(c.theme, "white") assert_equal(c.renderer, "canvas")
def generate_treemap_html(cur, title, key_field_name, area_field_name, click_link, area_data_name='数量', area_data_unit='个'): data, item_opts = [], [] min_rise = 100 max_rise = -100 for row in cur.fetchall(): item = get_dict_row(cur, row) rise_value = item['涨跌'] if rise_value > max_rise: max_rise = rise_value if rise_value < min_rise: min_rise = rise_value if rise_value > 0: rise = '\n+{}%'.format(rise_value) rich = { 'name': { 'fontSize': 14, 'color': '#000' }, '涨跌': { 'fontSize': 14, 'fontWeight': 'bolder', "align": "center", 'color': '#FF0000' } } tree_item = opts.TreeMapItemStyleOpts(color_alpha=1, color='rgb(255,0,0)', border_color='#fff') else: rise = '\n{}%'.format(rise_value) rich = { 'name': { 'fontSize': 14, 'color': '#000' }, '涨跌': { 'fontSize': 14, 'fontWeight': 'bolder', "align": "center", 'color': '#2E8B57' } } tree_item = opts.TreeMapItemStyleOpts(color_alpha=1, color='rgb(60,179,113)', border_color='#fff') data.append( opts.TreeItem( name=item[key_field_name], # value 包含持仓占比和涨跌幅两项数据 value=[item[area_field_name], rise_value], label_opts=opts.LabelOpts(position='insideBottomLeft', formatter='{name|{b}}{rise|%s}' % rise, rich=rich))) item_opts.append(tree_item) color_range, rise_range = calc_range(max_rise, min_rise) tooltip_js = """function (param) { const color = param.value[1] > 0 ? '#FF0000' : '#2E8B57'; const detail_style = `color:${color};`; const msgContent = `<div style='width:fit-content;height:fit-content;'> ${param.name}<br/> """ + area_data_name + """: <span style='color:'#fff';'> ${param.value[0]} """ + area_data_unit + """  </span><br/> 涨跌: <span style='${detail_style};'> ${param.value[1]} %  </span><br/> <div>`; return msgContent} """ tp = TreeMap(init_opts=opts.InitOpts( theme='white', width='1424px', height='700px', chart_id='cb_tree_map')) tp.add_js_funcs( """ chart_cb_tree_map.on('click', function(params){ // alert(params) window.location.replace('""" + click_link + """?key=' + encodeURIComponent(params['data']['name']) + '&rise=' + params['data']['value'][1] + '#cb_detail_list') }) """) tp.add( 'ALL', data, roam=False, node_click='link', width='90%', breadcrumb_opts=opts.TreeMapBreadcrumbOpts(is_show=False), levels=[ opts.TreeMapLevelsOpts( treemap_itemstyle_opts=opts.TreeMapItemStyleOpts( gap_width=1, stroke_width=1, stroke_color='#fff'), color_mapping_by='value', ) ], tooltip_opts=opts.TooltipOpts( is_show=True, formatter=JsCode(tooltip_js), textstyle_opts=opts.TextStyleOpts(font_size=14)), color_mapping_by='value', ) tp.set_global_opts( title_opts=opts.TitleOpts(title=title, pos_left='center', pos_top='30px'), legend_opts=opts.LegendOpts(is_show=False), visualmap_opts=opts.VisualMapOpts( is_show=False, type_='color', min_=min_rise, max_=max_rise, range_color=color_range, # 指定使用的数据维度 dimension=1, is_piecewise=True, pieces=rise_range), ) return tp.render_embed('template.html', env)