def test_tree_base(fake_writer): data = [ { "children": [ {"name": "B"}, { "children": [ {"children": [{"name": "I"}], "name": "E"}, {"name": "F"}, ], "name": "C", }, { "children": [ {"children": [{"name": "J"}, {"name": "K"}], "name": "G"}, {"name": "H"}, ], "name": "D", }, ], "name": "A", } ] c = Tree().add("", data) c.render() _, content = fake_writer.call_args[0] eq_(c.theme, "white") eq_(c.renderer, "canvas")
def test_tree_base(): data = [ { "children": [ {"name": "B"}, { "children": [ {"children": [{"name": "I"}], "name": "E"}, {"name": "F"}, ], "name": "C", }, { "children": [ {"children": [{"name": "J"}, {"name": "K"}], "name": "G"}, {"name": "H"}, ], "name": "D", }, ], "name": "A", } ] c = Tree().add("", data) eq_(c.theme, "white") eq_(c.renderer, "canvas") c.render()
def test_tree_options(fake_writer): c = Tree().add( series_name="tree", data=TEST_DATA, orient="BT", initial_tree_depth=1, label_opts=opts.LabelOpts(), leaves_label_opts=opts.LabelOpts(), ) c.render() _, content = fake_writer.call_args[0] assert_in("orient", content) assert_in("initialTreeDepth", content) assert_in("label", content) assert_in("leaves", content)
def tree_rl() -> Tree: with open(os.path.join("fixtures", "flare.json"), "r", encoding="utf-8") as f: j = json.load(f) c = (Tree().add("", [j], collapse_interval=2, orient="RL").set_global_opts( title_opts=opts.TitleOpts(title="Tree-右左方向"))) return c
def tree_base() -> Tree: data = [ { "children": [ {"name": "B"}, { "children": [ {"children": [{"name": "I"}], "name": "E"}, {"name": "F"}, ], "name": "C", }, { "children": [ {"children": [{"name": "J"}, {"name": "K"}], "name": "G"}, {"name": "H"}, ], "name": "D", }, ], "name": "A", } ] c = ( Tree() .add("", data) .set_global_opts(title_opts=opts.TitleOpts(title="Tree-基本示例")) ) return c
def tree_base() -> Tree: # data = [ # { # "children": [ # {"name": "B"}, # { # "children": [ # {"children": [{"name": "I"}], "name": "E"}, # {"name": "F"}, # ], # "name": "C", # }, # { # "children": [ # {"children": [{"name": "J"}, {"name": "K"}], "name": "G"}, # {"name": "H"}, # ], # "name": "D", # }, # ], # "name": "A", # } # ] data = addchildren(data, json.dumps(foo)) c = ( Tree() .add("", data) .set_global_opts(title_opts=opts.TitleOpts(title="Tree-基本示例")) ) return c
def tree__cs_level(): data = analysis_data.get_cs_level() c = (Tree(init_opts=opts.InitOpts(height='3500px')).add( "", data, label_opts=opts.LabelOpts(position='insideRight')).set_global_opts( title_opts=opts.TitleOpts(title="计科学科评估树"))) return c
def test_tree_base(): data = [{ "children": [ { "name": "B" }, { "children": [ { "children": [{ "name": "I" }], "name": "E" }, { "name": "F" }, ], "name": "C", }, { "children": [ { "children": [{ "name": "J" }, { "name": "K" }], "name": "G" }, { "name": "H" }, ], "name": "D", }, ], "name": "A", }] c = Tree().add("", data) assert c.theme == "white" assert c.renderer == "canvas" c.render("render.html")
def tree_map(): c = ( Tree() .add("", data) .set_global_opts(title_opts={'text':'档案信息比对结果:'}) ) m = [] m.append(c) return m
def parse_data(): users = [] user1 = User(children=None, account_id='MY000001225-1', name='longs001-1', card_id='41082619760103451X') values = data.loc[data['客户账号'] == 'MY000001225-1'] parse_user(user1, values) print(user1.as_dict()) result = [user1.as_dict()] tree = ( Tree().add("", result, orient="TB").set_global_opts(title_opts=opts.TitleOpts(title="层级关系图")) )
def genTreeLayout(self,json,title='树形示例'): ''' 结点之间的关系图title ''' c = ( Tree() .add("", [json], collapse_interval=2, layout="radial") .set_global_opts(title_opts=opts.TitleOpts(title=title)) ) chart_name = f'static/chart{self.index}_tree' make_snapshot(snapshot,c.render(f'{chart_name}.html'),f'{chart_name}.png',is_remove_html=True) self.index += 1
def tree_base(ge) -> Tree: c = ( Tree() # .add("", data) .add( "", data=addchildren(data, json.dumps(ge)), symbol_size=16, # collapse_interval = 8, initial_tree_depth=-1) # .add("", data , initial_tree_depth = -1) .set_global_opts(title_opts=opts.TitleOpts(title="Tree-动态示例"))) return c
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 render_eacharts_html(data): c = (Tree().add( "", [data], collapse_interval=2, orient="TB", label_opts=opts.LabelOpts( position="top", horizontal_align="right", vertical_align="middle", rotate=-90, ), ).set_global_opts(title_opts=opts.TitleOpts( title="Tree-上下方向")).render("static/tree_bottom_top.html"))
def tree(): f = open("/home/jiawang/share/django/fcexplorer/data/tree.json", "r") data = f.read() f.close() return (Tree(init_opts=opts.InitOpts(width="1400px", height="800px")).add( series_name="", data=[data], pos_top="18%", pos_bottom="14%", layout="radial", symbol="emptyCircle", symbol_size=7, ).set_global_opts( tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove")))
def _create_tree(): TEST_DATA = [{ "children": [ { "name": "B" }, { "children": [{ "children": [{ "name": "I" }], "name": "E" }, { "name": "F" }], "name": "C", }, { "children": [ { "children": [{ "name": "J" }, { "name": "K" }], "name": "G" }, { "name": "H" }, ], "name": "D", }, ], "name": "A", }] return Tree().add( series_name="tree", data=TEST_DATA, orient="LR", initial_tree_depth=3, label_opts=opts.LabelOpts(), leaves_label_opts=opts.LabelOpts(), )
def tree_tb() -> Tree: with open(os.path.join("fixtures", "flare.json"), "r", encoding="utf-8") as f: j = json.load(f) c = (Tree().add( "", [j], collapse_interval=2, orient="TB", label_opts=opts.LabelOpts( position="top", horizontal_align="right", vertical_align="middle", rotate=-90, ), ).set_global_opts(title_opts=opts.TitleOpts(title="Tree-上下方向"))) return c
def treeChart(df): tree = Tree() tree.add('', df, orient="TB", label_opts=opts.LabelOpts( position="top", horizontal_align="right", vertical_align="middle", rotate=-90, ), ) tree.set_global_opts(title_opts=opts.TitleOpts(title="Tree")) return tree
def tree_image() -> Tree: data = [{ "children": [ { "name": "收藏" }, { "children": [{ "children": [{ "name": "点赞" }], "name": "投币" }, { "name": "分享" }], "name": "点赞", }, { "children": [ { "children": [{ "name": "点踩" }, { "name": "举报" }], "name": "举报" }, { "name": "小黑屋" }, ], "name": "点踩", }, ], "name": "观看", }] c = (Tree().add("", data).set_global_opts(title_opts=opts.TitleOpts(title=""))) return c
if num>limit: for son1 in cut[0]["children"]: for son2 in son1["children"][::-1]: son1["children"].remove(son2) num-=1 if num==limit: break for son1 in cut[0]["children"]: for son2 in son1["children"]: num=0 for son3 in son2["children"]: num+=1 if num>limit: for son1 in cut[0]["children"]: for son2 in son1["children"]: for son3 in son2["children"][::-1]: son2["children"].remove(son3) num-=1 if num==limit: break except: print("Please enter number!") tree=( Tree() .add("",cut) .set_global_opts(title_opts=opts.TitleOpts(title="关系图")) ) tree.render("E:/wamp64/www/lcy/1.html")
def test_tree_base(fake_writer): c = Tree().add("", TEST_DATA) c.render() _, content = fake_writer.call_args[0] assert_equal(c.theme, "white") assert_equal(c.renderer, "canvas")
from pywebio.output import put_html import json from pyecharts import options as opts from pyecharts.charts import Tree with open("flare.json", "r", encoding="utf-8") as f: j = json.load(f) c = (Tree().add("", [j], collapse_interval=2, layout="radial").set_global_opts( title_opts=opts.TitleOpts(title="Tree-Layout"))) c.width = "100%" put_html(c.render_notebook())
import pyecharts.options as opts from pyecharts.charts import Tree """ Gallery 使用 pyecharts 1.1.0 参考地址: https://echarts.baidu.com/examples/editor.html?c=tree-radial 目前无法实现的功能: 1、 """ async def get_json_data(url: str) -> dict: async with ClientSession(connector=TCPConnector(ssl=False)) as session: async with session.get(url=url) as response: return await response.json() # 获取官方的数据 data = asyncio.run( get_json_data( url="https://echarts.baidu.com/examples/data/asset/data/flare.json")) (Tree(init_opts=opts.InitOpts(width="1400px", height="800px")).add( series_name="", data=[data], pos_top="18%", pos_bottom="14%", layout="radial", symbol="emptyCircle", symbol_size=7, ).set_global_opts(tooltip_opts=opts.TooltipOpts( trigger="item", trigger_on="mousemove")).render("render/radial_tree.html"))
from pywebio.output import put_html import json from pyecharts import options as opts from pyecharts.charts import Tree with open("flare.json", "r", encoding="utf-8") as f: j = json.load(f) c = (Tree().add("", [j], collapse_interval=2).set_global_opts( title_opts=opts.TitleOpts(title="Tree-左右方向"))) c.width = "100%" put_html(c.render_notebook())
class MCT(list): #there are 12 weeks, 10 SKUs, and we set C to 2 def __init__(self, maxLayer=12, maxNum=10, ensemble=False, C=2): self.maxLayer = maxLayer self.maxNum = maxNum self.ensemble = ensemble self.root = StatusNode(0, status=[0, 0, 0, maxNum]) self.root.value = 0 self.nodeList = [] self.meanProfit = 0 self.stdProfit = 0 self.C = C ### def checkChild(self, checkedNode, checkedStatus): if len(checkedNode.childList) == 0: return False if type(checkedNode) == int: myNode = self.nodeList[checkedNode] else: myNode = checkedNode for childI in checkedNode.childList: if self.nodeList[childI].status == checkedStatus: return True return False #find the childnode whose status equals to the value we want def findChild(self, checkedNode, checkedStatus): if len(checkedNode.childList) == 0: return None if type(checkedNode) == int: myNode = self.nodeList[checkedNode] else: myNode = checkedNode for childI in checkedNode.childList: if self.nodeList[childI].status == checkedStatus: return self.nodeList[childI] return None #update the times we checked/passed/selected a node def updateChecked(self, myNode: DecisionNode): tmpTravelNode = myNode while tmpTravelNode is not None: tmpTravelNode.checked += 1 tmpTravelNode = tmpTravelNode.parent def training(self, myX, myY, maxIter=5): ''' myX:ValueB+ReturnB ''' decisionList = list(set(myY.tolist())) print("training ...") self.nodeList = [self.root] #start iteration for iter in range(maxIter): #-for every iteration print("第{}轮迭代开始".format(iter + 1)) newStatusList = [self.root] for layerI in range(self.maxLayer): print("第{}周开始".format(layerI + 1)) #--for every layer #--new data newData = myX[iter * self.maxLayer + layerI, :] #--next week #--decision nodes newDecisionList = [] if self.maxNum > 0: #--the SKU was sold out if len(newStatusList) == 0: print("the SKU was sold out in all the way") break #--whether to generalize the decision node for statusNodeItem in newStatusList: if len(statusNodeItem.childList) == 0: #-----if the status doesn't have decision child for decisionItem in decisionList: #------set the decision node tmpDecisionNode = DecisionNode( decisionItem, parent=statusNodeItem) #------update the checked on the path self.updateChecked(tmpDecisionNode) #------add the node to the node list self.nodeList.append(tmpDecisionNode) #------add the node to the child list statusNodeItem.childList.append( len(self.nodeList) - 1) #-----add the node to the newDecisionNodeList newDecisionList.append(tmpDecisionNode) else: for decisionI in statusNodeItem.childList: #---update checked of the node tmpTravelNode = statusNodeItem self.updateChecked(tmpTravelNode) newDecisionList.append( self.nodeList[decisionI]) #--set the newStatusList newStatusList = [] #--find the decision node with the largest ucb maxUCB = max([ newDecisionNodeItem.ucb for newDecisionNodeItem in newDecisionList ]) #--status nodes for decisionNodeItem in newDecisionList: if decisionNodeItem.ucb == maxUCB: self.updateChecked(decisionNodeItem) #---status in this situation if decisionNodeItem.parent.status[3] - np.sum( newData[:7] >= decisionNodeItem.decision ) >= 0: #----if there is enough deposit tmpStatus=[np.sum(newData[:7]>=decisionNodeItem.decision),\ np.sum(newData[:7]<decisionNodeItem.decision),\ np.sum(newData[7:]>0),\ decisionNodeItem.parent.status[3]-np.sum(newData[:7]>=decisionNodeItem.decision)] else: #----if there is not enough deposit tmpStatus=[decisionNodeItem.parent.status[3],\ 7-decisionNodeItem.parent.status[3],\ np.sum(newData[7:]>0),\ 0] if tmpStatus[0] + tmpStatus[1] != 7: print(newData, decisionNodeItem.decision) #---the decision doesn't have the status node if self.checkChild(decisionNodeItem, tmpStatus) == False: #----new status node tmpStatusNode=StatusNode(decisionNodeItem.decision,\ status=tmpStatus,\ parent=decisionNodeItem) #----add the status node into node list self.nodeList.append(tmpStatusNode) #----add the status node into the child list of the decision node decisionNodeItem.childList.append( len(self.nodeList) - 1) else: #-----if the status already exists, change tmpNode into it tmpStatusNode = self.findChild( decisionNodeItem, tmpStatus) #----update the parents' value self.updateChecked(tmpStatusNode) tmpTravelNode = tmpStatusNode tmpAggValue = 0 while tmpTravelNode.parent is not None: if type(tmpTravelNode) == StatusNode: tmpTravelNode.value = ( tmpTravelNode.value * tmpTravelNode.checked + decisionNodeItem.decision * tmpTravelNode.status[0] + tmpAggValue ) / (tmpTravelNode.checked + 1) tmpAggValue = tmpTravelNode.value else: tmpTravelNode.value = ( tmpTravelNode.value * tmpTravelNode.checked + np.max([ self.nodeList[childI].value * self.nodeList[childI].checked / tmpTravelNode.checked for childI in tmpTravelNode.childList ])) / (tmpTravelNode.checked + 1) # print(self.nodeList[tmpTravelNode.childList[0]].checked/tmpTravelNode.checked) tmpTravelNode = tmpTravelNode.parent #------add the node to newStatusList if tmpStatusNode not in newStatusList and tmpStatusNode.status[ 3] > 0: newStatusList.append(tmpStatusNode) #------update the ucb if find the tail node if tmpStatusNode.status[3] == 0: #--backpropagation for this iteration self.BPIter(tmpStatusNode) #only leave the status node with decision node with highest ucb maxUcb = 0 for statusNodeItem in newStatusList: if statusNodeItem.parent.ucb > maxUcb: maxUcb = statusNodeItem.parent.ucb newStatusI = 0 while newStatusI < len(newStatusList): if newStatusList[newStatusI].parent.ucb < maxUcb: newStatusList.pop(newStatusI) newStatusI -= 1 newStatusI += 1 print("第{}周结束".format(layerI + 1)) #calculate backwards the ucb of each node def BPIter(self, myNode): tmpNode = myNode while tmpNode.parent is not None: #-update the ucb while BP tmpNode.ucb = tmpNode.value + self.C * np.sqrt( np.log(tmpNode.parent.checked) / tmpNode.checked) #-update the usb of the cousins of the tmpNode for childItem in tmpNode.parent.childList: if tmpNode is not self.nodeList[childItem]: self.nodeList[childItem].ucb = self.nodeList[ childItem].value + self.C * np.sqrt( np.log(self.nodeList[childItem].parent.checked) / self.nodeList[childItem].checked) tmpNode = tmpNode.parent ### def integrateTree(self, myNode): myDict = {} if type(myNode) == DecisionNode: myDict[ "name"] = "D,ucb:{:.2f},price:{},value:{:.2f},checked:{}".format( myNode.ucb, myNode.decision, myNode.value, myNode.checked) else: if myNode.parent != None: myDict[ "name"] = "S,status:{},value:{:.2f},weight:{:.2f}".format( myNode.status, myNode.value, myNode.checked / myNode.parent.checked) else: myDict["name"] = "root" myDict["children"] = [] if len(myNode.childList) != 0: for childI in myNode.childList: myDict["children"].append( self.integrateTree(self.nodeList[childI])) return myDict def plotModel(self): self.tree = Tree() self.echartTree = [self.integrateTree(self.root)] self.tree.add("", self.echartTree) self.tree.render() def saveModel(self): with open("model/myModel.pkl", "wb+") as myModelFile: pkl.dump(self, myModelFile)
d["name"] = i l.append(d) # print(group['主题']) d2["children"] = l d2["name"] = name data2.append(d2) # 最外层树 dic2 = {} dic2["children"] = data2 dic2["name"] = "关键词" data.append(dic2) print(data) # 需要调整画布大小 tree = Tree(init_opts=opts.InitOpts(width='2000px', height='15000px')) # 两个树分支的距离增大 tree.add("", data, collapse_interval=100) tree.set_global_opts(title_opts=opts.TitleOpts(title="LDA主题模型")) tree.render(u'./tree.html') # 用如下程序也行 # C = Collector() # # # @C.funcs # def tree_base() -> Tree: # # c = ( # Tree() # .add("", data, collapse_interval=100)
Tree(init_opts = opts.InitOpts(width = "1920px",height = "1080px",theme = ThemeType.DARK)) .add( "", data = handleData(data,0), pos_top = 30, pos_bottom = 0, pos_left = 0, pos_right = 0, layout = "radial", symbol = "circle", symbol_size = 10, initial_tree_depth = 2, is_expand_and_collapse = True, itemstyle_opts = opts.ItemStyleOpts(border_width = 1), label_opts = opts.LabelOpts( color = "#fff", font_size = 10, position = "inside", font_family = "SourceHanSansCN", rotate = 0 ), tooltip_opts = opts.TooltipOpts( trigger = "item", trigger_on = "mousemove", background_color = "rgba(1,70,86,1)", border_color = "rgba(0,246,255,1)", border_width = 0.5, textstyle_opts = opts.TextStyleOpts(font_size = 10), ) ) .set_global_opts( title_opts = opts.TitleOpts(title = "2019年常驻人口数前十的省份及城市(单位:万人)"), ) .render("2019_china_population.html")
import json from pyecharts import options as opts from pyecharts.charts import Tree with open("flare.json", "r", encoding="utf-8") as f: j = json.load(f) c = (Tree().add("", [j], collapse_interval=2).set_global_opts(title_opts=opts.TitleOpts( title="Tree-左右方向")).render("tree_left_right.html"))
from pywebio.output import put_html import json from pyecharts import options as opts from pyecharts.charts import Tree with open("flare.json", "r", encoding="utf-8") as f: j = json.load(f) c = (Tree().add( "", [j], collapse_interval=2, orient="BT", label_opts=opts.LabelOpts( position="top", horizontal_align="right", vertical_align="middle", rotate=-90, ), ).set_global_opts(title_opts=opts.TitleOpts(title="Tree-下上方向"))) c.width = "100%" put_html(c.render_notebook())
def plotModel(self): self.tree = Tree() self.echartTree = [self.integrateTree(self.root)] self.tree.add("", self.echartTree) self.tree.render()