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 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 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 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
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 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
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
"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()
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')
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'), leaf_depth=1) map.render('map(1).html')
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)