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 
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"))
Пример #3
0
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 + """:&nbsp<span style='color:'#fff';'>&nbsp${param.value[0]}&nbsp""" + area_data_unit + """&nbsp&nbsp</span><br/>
            涨跌:&nbsp<span style='${detail_style};'>&nbsp${param.value[1]}&nbsp%&nbsp&nbsp</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)