def test_graph_draggable_and_symbol_size(fake_writer): nodes = [ { "name": "结点1", "symbolSize": 10 }, { "name": "结点2", "symbolSize": 20 }, { "name": "结点3", "symbolSize": 30 }, { "name": "结点4", "symbolSize": 40 }, ] links = [] for i in nodes: for j in nodes: links.append({"source": i.get("name"), "target": j.get("name")}) c = Graph().add("", nodes, links, repulsion=8000, is_draggable=True, symbol_size=50) c.render() _, content = fake_writer.call_args[0] assert_in("draggable", content) assert_in("symbolSize", content)
def test_graph_base(fake_writer): nodes = [ { "name": "结点1", "symbolSize": 10 }, { "name": "结点2", "symbolSize": 20 }, { "name": "结点3", "symbolSize": 30 }, { "name": "结点4", "symbolSize": 40 }, ] links = [] for i in nodes: for j in nodes: links.append({"source": i.get("name"), "target": j.get("name")}) c = Graph().add("", nodes, links, repulsion=8000) c.render() _, content = fake_writer.call_args[0] assert_equal(c.theme, "white") assert_equal(c.renderer, "canvas")
def test_graph_edge_label_opts(fake_writer): nodes = [ { "name": "结点1", "symbolSize": 10 }, { "name": "结点2", "symbolSize": 20 }, { "name": "结点3", "symbolSize": 30 }, { "name": "结点4", "symbolSize": 40 }, ] links = [] for i in nodes: for j in nodes: links.append({"source": i.get("name"), "target": j.get("name")}) c = Graph().add("", nodes, links, repulsion=4000, edge_label=opts.LabelOpts(is_show=True)) c.render() _, content = fake_writer.call_args[0] assert_in("edgeLabel", content)
def __init__(self, width="1200px", height="800px"): self.graph = Graph(init_opts=opts.InitOpts( width=width, height=height, bg_color='rgba(255,255,255)')).set_global_opts( # 设置显示工具栏 toolbox_opts=opts.ToolboxOpts(feature=opts.ToolBoxFeatureOpts( save_as_image=opts.ToolBoxFeatureSaveAsImageOpts( name='networks', # 设置工具栏图片保存的文件名 ), ))) self.line_width = 1
def drawGraph(nodes, links, name): # 图表初始化配置 init_opts = opts.InitOpts(page_title=name, height="700px") g = Graph(init_opts=init_opts) # 标题配置 title = opts.TitleOpts(title=name, pos_left='center') # 图例配置 legend_opts = opts.LegendOpts(pos_top="5%", pos_left="15%") # 工具箱配置 # 工具箱配置 toolbox_opts = opts.ToolboxOpts() g.set_global_opts( title_opts=title, legend_opts=legend_opts, toolbox_opts=toolbox_opts, ) g.add( "", nodes, links, repulsion=8000, linestyle_opts=opts.LineStyleOpts(curve=0.2), ) g.render("{0}.html".format(name))
def draw(self): nodes_data = [] sort_people = sorted(self.people.items(), key=lambda item: item[1], reverse=True) for key, value in sort_people: nodes_data.append(opts.GraphNode(name=key, symbol_size=value / 80)) # 节点出现次数 links_data = [] for key, key_value in self.relationship.items(): for key2, value in key_value.items(): links_data.append( opts.GraphLink(source=key, target=key2, value=value)) # 节点之间权值 c = Graph(init_opts=opts.InitOpts(width="1200px", height="800px")) # 调用类 c.add( "", nodes_data, # 关系图节点数据项列表 links_data, # 关系图节点间关系数据项列表 layout="circular", repulsion=800, # 节点之间的斥力因子 edge_length=100, # 边的两个节点之间的距离 linestyle_opts=opts.LineStyleOpts(curve=0.3), # 关系边的公用线条样式 label_opts=opts.LabelOpts(position="right"), ) c.set_global_opts(title_opts=opts.TitleOpts(title="人物图谱")) c.render("人物图谱.html")
def test_graph_base(): nodes = [ {"name": "结点1", "symbolSize": 10}, {"name": "结点2", "symbolSize": 20}, {"name": "结点3", "symbolSize": 30}, {"name": "结点4", "symbolSize": 40}, ] links = [] for i in nodes: for j in nodes: links.append({"source": i.get("name"), "target": j.get("name")}) c = Graph().add("", nodes, links, repulsion=8000) assert c.theme == "white" assert c.renderer == "canvas" c.render("render.html")
def draw_chain_decomposition(): chain_decomposition = list(nx.chain_decomposition(G)) longest_chain = sorted(chain_decomposition, key=lambda x: (len(x)), reverse=True)[0] nodes = [opts.GraphNode(name=G.nodes[x[0]]['name']) for x in longest_chain] nodes.append( opts.GraphNode(name=G.nodes[longest_chain[-1][1]]['name'], label_opts=opts.LabelOpts(color='#d48265'))) nodes[0] = opts.GraphNode(name=G.nodes[longest_chain[0][0]]['name'], label_opts=opts.LabelOpts(color='#749f83')) links = [ opts.GraphLink(source=G.nodes[x]['name'], target=G.nodes[y]['name']) for x, y in longest_chain ] c = (Graph().add( series_name="", nodes=nodes, links=links, layout='force', is_roam=True, is_focusnode=True, label_opts=opts.LabelOpts(is_show=False), is_draggable=True, repulsion=100, linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3, opacity=0.7), )) c.render("Graph with longest chain.html")
def draw_the_whole_graph(): nodes = [ opts.GraphNode(name=G.nodes[x]['name'], value=G.degree[x], symbol_size=G.degree[x] / 10, category=G.nodes[x]['E_numbers']) for x in G.nodes ] links = [ opts.GraphLink(source=G.nodes[x]['name'], target=G.nodes[y]['name']) for x, y in G.edges ] categories = [{'name': 'Erdos_number:' + str(x)} for x in range(3)] c = ( Graph().add( series_name="", nodes=nodes, links=links, layout='circular', is_roam=True, is_focusnode=True, label_opts=opts.LabelOpts(is_show=False), is_draggable=True, categories=categories, # repulsion=100 # linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3, opacity=0.7), ).set_global_opts(title_opts=opts.TitleOpts( title="Graph with \n authors degrees"))) c.render("Graph with authors degrees.html")
def graph(model_name, model) -> Graph: (categories, nodes, links) = get_data(model_name, model) c = (Graph(init_opts=opts.InitOpts(width="1600px", height="800px")).add( "", nodes=nodes, links=links, categories=categories, gravity=0.01, repulsion=300, linestyle_opts=opts.LineStyleOpts(color="black", curve=0.2), label_opts=opts.LabelOpts(is_show=True, position='inside', font_size=20), is_draggable=True, is_rotate_label=True, is_focusnode=True, layout="force", edge_length=200, edge_label=opts.LabelOpts(is_show=True, position="middle", font_size=15, formatter="{c}"), edge_symbol=[None, 'arrow']).set_global_opts( legend_opts=opts.LegendOpts(is_show=True), title_opts=opts.TitleOpts(title=str(model)), ).dump_options_with_quotes()) return c
def graph_weibo() -> Graph: with open(os.path.join("..\\000LocalData\\echart_example\\", "weibo.json"), "r", encoding="utf-8") as f: j = json.load(f) nodes, links, categories, cont, mid, userl = j c = (Graph(init_opts=opts.InitOpts(width="1920px", height="900px", page_title="Graph-微博转发关系图", theme=ThemeType.INFOGRAPHIC)).add( "", nodes, links, categories, repulsion=50, linestyle_opts=opts.LineStyleOpts( curve=0.2), label_opts=opts.LabelOpts( is_show=False), ).set_global_opts( legend_opts=opts.LegendOpts( orient="vertical", pos_left="1%", pos_top="5%", ), title_opts=opts.TitleOpts( title="Graph-微博转发关系图"), )) return c
def graph() -> Graph: nodes_data = [ opts.GraphNode(name="氢气车", symbol_size=10, value=10), opts.GraphNode(name="加注机", symbol_size=20, value=20), opts.GraphNode(name="储氢罐", symbol_size=30, value=30), opts.GraphNode(name="压缩机", symbol_size=40, value=40), opts.GraphNode(name="长管拖车", symbol_size=40, value=50), ] links_data = [ opts.GraphLink(source="氢气车", target="加注机", value=10), opts.GraphLink(source="加注机", target="储氢罐", value=10), opts.GraphLink(source="储氢罐", target="压缩机", value=10), opts.GraphLink(source="压缩机", target="长管拖车", value=10), opts.GraphLink(source="长管拖车", target="氢气车", value=10), ] c = ( Graph().add( "", nodes_data, links_data, repulsion=4000, is_draggable=True, # label_opts=opts.LabelOpts( # formatter="压力:{@source} Mpa" # ), edge_label=opts.LabelOpts(is_show=True, position="middle", formatter="压差:{@source} Mpa"), itemstyle_opts=opts.ItemStyleOpts(color='#4ed497')) # .set_global_opts( # title_opts=opts.TitleOpts(title="Graph-GraphNode-GraphLink-WithEdgeLabel") # ) .dump_options_with_quotes()) return c
def graph_npm_dependencies() -> Graph: with open(os.path.join("fixtures", "npmdepgraph.json"), "r", encoding="utf-8") as f: j = json.load(f) nodes = [{ "x": node["x"], "y": node["y"], "id": node["id"], "name": node["label"], "symbolSize": node["size"], "itemStyle": { "normal": { "color": node["color"] } }, } for node in j["nodes"]] edges = [{ "source": edge["sourceID"], "target": edge["targetID"] } for edge in j["edges"]] c = (Graph(init_opts=opts.InitOpts(width="1000px", height="600px")).add( "", nodes=nodes, links=edges, layout="none", label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3, opacity=0.7), ).set_global_opts(title_opts=opts.TitleOpts( title="Graph-NPM Dependencies"))) return c
def graph_with_opts(nodes, links,categories,district,school_name): c = ( Graph(init_opts=opts.InitOpts(width='1750px')) .add("", nodes, links,categories) .set_global_opts(title_opts=opts.TitleOpts(title=f"{district}-{school_name}\n统招志愿关系图谱")) ) return c
def draw_dp(text, mat_rel_type, file='dp.html'): n_rel = 1 + len(text) nodes_data = [] for i, x in enumerate(['H'] + list(text) + ['T']): nodes_data.append( opts.GraphNode(name=f'{x}_{i}', x=i * 50, y=100, value=x, symbol_size=10)) links_data = [] for i in range(n_rel): for j in range(n_rel): if mat_rel_type[i][j]: links_data.append( opts.GraphLink(source=i, target=j, value=str(mat_rel_type[i][j]))) c = (Graph().add( "", nodes_data, links_data, label_opts=opts.LabelOpts(is_show=True, formatter="{c}"), linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.5, opacity=0.7), edge_label=opts.LabelOpts(is_show=True, position="middle", formatter="{c}", font_size=8), layout="none", is_roam=True, ).set_global_opts(title_opts=opts.TitleOpts(title="依存")).render(file))
def graph_weibo() -> Graph: with open("weibo.json", "r", encoding='utf-8') as f: j = json.load(f) nodes, links, categories = j print(len(nodes)) nodes = nodes[:2000] # print(nodes) c = ( Graph() .add( "", nodes, links, categories, repulsion=50, linestyle_opts=opts.LineStyleOpts(curve=0.2), label_opts=opts.LabelOpts(is_show=False), ) .set_global_opts( legend_opts=opts.LegendOpts(is_show=False), title_opts=opts.TitleOpts(title="Graph-微博评论关系图"), ) ) return c
def graph_npm_dependencies(): with open('data/npmdepgraph.json', 'r', encoding='utf-8') as f: j = json.load(f) nodes = [ { 'x': node['x'], 'y': node['y'], 'id': node['id'], 'name': node['label'], 'symbolSize': node['size'], 'itemStyle': {'normal': {'color': node['color']}} } for node in j['nodes'] ] edges = [ {'source': edge['sourceID'], 'target': edge['targetID']} for edge in j['edges'] ] c = ( Graph() .add('', nodes=nodes, links=edges, layout='none', label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3, opacity=0.7)) .set_global_opts(title_opts=opts.TitleOpts(title='Graph-NPM Dependencies')) ) return c
def _graph_contracted_signed(config:dict=None, nodes:list=None) -> Graph: nodes_show = [opts.GraphNode(name=node, x=nodes[node]['pos'][0], y=nodes[node]['pos'][1], symbol_size=10, category='level_'+str(nodes[node]['color'])) for node in nodes] links = [] def _get_categories(): try: _categories ={nodes[node]['color'] for node in nodes} categories = [opts.GraphCategory(name='level_'+str(category)) for category in _categories] except: categories = [ opts.GraphCategory(name='c_'+ str(index)) for index in range(len(nodes)) ] finally: return categories print(_get_categories()) c = ( Graph() .add("", nodes_show, links, _get_categories(), edge_symbol=['', 'arrow'], edge_symbol_size=10, layout=config['layout'] if 'layout' in config else 'none', repulsion=4000, emphasis_itemstyle_opts=config['emphasis_linestyleopts'] if 'emphasis_linestyleopts' in config else None ) .set_global_opts(title_opts=opts.TitleOpts(title=config['title'] if 'title' in config else "")) ) return c
def graph_chart(node_list=None, link_list=None, category_list=None) -> Graph: """绘制【星级商铺及相应菜品推荐】的关系图需求 9.1 设置主题"purple-passion"; 9.2 图例系列名称设置为空,整体布局呈现圆形,标签可依照节点和线的分布旋转调整, 边的颜色和起点节点颜色相同,弯曲度为0.3; 9.3 图例垂直方向摆放,举例图片左侧和顶部的相对举例分别为3%和20%,设置标题为"星级推荐"; 9.4 return返回c; :param node_list: 星级信息以及商铺信息的分类、带权节点 :param link_list: 节点之间的连线情况 :param category_list: 星级分类种别 :return: 绘制好的关系图对象 """ c = (Graph(init_opts=opts.InitOpts( theme=ThemeType.PURPLE_PASSION)).set_global_opts( title_opts=opts.TitleOpts(title="星级推荐"), legend_opts=opts.LegendOpts(orient="vertical", pos_left="3%", pos_top="20%")).add( series_name="", nodes=node_list, links=link_list, categories=category_list, layout="circular", is_rotate_label=True, linestyle_opts=opts.LineStyleOpts( color="source", curve=0.3))) return c
def draw_k_cores(): k_cores = nx.k_core(G) nodes = [ opts.GraphNode(name=k_cores.nodes[x]['name'], value=k_cores.degree[x], symbol_size=k_cores.degree[x]) for x in k_cores.nodes ] links = [ opts.GraphLink(source=k_cores.nodes[x]['name'], target=k_cores.nodes[y]['name']) for x, y in k_cores.edges ] c = ( Graph().add( series_name="", nodes=nodes, links=links, layout='force', is_roam=True, is_focusnode=True, label_opts=opts.LabelOpts(is_show=False), is_draggable=True, repulsion=10000, # linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3, opacity=0.7), )) c.render("k_cores_subgraph.html")
def draw_graph(data_, title): nodes_ = [ { "name": node_["label"], "symbol": "circle", "symbolSize": int(node_["weight"] / 10) + 5, "value": node_["weight"], # "itemStyle": {"normal": {"color": node["color"]}}, } for node_ in data_["nodes"] ] edges_ = [{ "source": edge[0], "target": edge[1], "value": lower_edge_weight["({0}, {1})".format(edge[0], edge[1])], "symbol": [None, "arrow"], "symbol_size": [0, 1] } for edge in data_["edges"]] (Graph(init_opts=opts.InitOpts(width="1600px", height="800px")).add( series_name="", nodes=nodes_, links=edges_, is_roam=True, is_focusnode=True, layout="force", is_selected=False, is_draggable=False, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3, opacity=0.7), ).set_global_opts(title_opts=opts.TitleOpts(title=title)).render( "./graphs/{0}.html".format(title)))
def seller_product_chart(): point_color = ['#000', '#0F0', '#00F', '#0FF', '#F0F', '#888', ] seller_product_link = [] seller_product_node = [] for s in Seller.objects.order_by('-order_num')[:10]: color = point_color[random.randint(0, len(point_color) - 1)] seller_product_node.append({"name": s.name, "symbolSize": 10, "itemStyle": {"normal": {"color": color}}}) for p in Product.objects.filter(seller=s)[:10]: seller_product_node.append({ "name": p.title, "symbolSize": 1, "itemStyle": {"normal": {"color": color}} }) seller_product_link.append({"source": s.name, "target": p.title}) graph = ( Graph(init_opts=opts.InitOpts( js_host='../static/js/', height='800%', width='1100px') ).add( "", seller_product_node, seller_product_link, repulsion=500, linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3, opacity=0.7), ).set_global_opts( title_opts=opts.TitleOpts(title="商家-产品关系图")) ) return graph.render_embed()
def draw(order): NN = make_nodes(order) EE = make_edges(order) nodes = [{ "id": str(node["id"]), "symbol": node["shape"], "name": "{Compment:" + node["label"] + "}, {" + "Title:" + node["value"] + "}", "symbolSize": node["size"], "itemStyle": { "normal": { "color": node["color"] } }, "value": node["id"], } for node in NN] edges = [{ "source": str(edge["From"]), "target": str(edge["To"]) } for edge in EE] c = (Graph(init_opts=opts.InitOpts()).add( "Bug-Inf", nodes=nodes, links=edges, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(curve=0.2), ).set_global_opts(title_opts=opts.TitleOpts(title="Recommond System Vis"))) return c
def graph_topology(res_json, opts_title_name) -> Graph: """ 绘制网络拓扑图 :param res_json: :param opts_title_name: :return: """ c = ( Graph(init_opts=opts.InitOpts(width="1920px", height="960px", page_title=opts_title_name, theme=ThemeType.SHINE)).add( "", res_json["nodes"], res_json["links"], res_json["categories"], # layout="circular", is_rotate_label=True, gravity=0.2, repulsion=100000, linestyle_opts=opts.LineStyleOpts( width=0.1), label_opts=opts.LabelOpts( is_show=False), ).set_global_opts( legend_opts=opts.LegendOpts( is_show=False), title_opts=opts.TitleOpts( title=opts_title_name), )) return c
def write_graph(self, words_sum, categories, nodes, links, title, render_name): ratio = self.symbol_szie(words_sum.max()) for i in range(len(words_sum)): nodes.append({ 'name': words_sum.index[i], 'value': str(words_sum.values[i]), 'symbolSize': str(words_sum.values[i] * ratio), 'category': 1 }) c = ( Graph(init_opts=opts.InitOpts( width='1200px', height='900px', page_title=title)). add( "", # 系列名称 nodes, # 关系图节点数据项列表 links, # 关系图节点间关系数据项列表 categories, # 关系图节点分类的类目列表 is_roam=False, # 是否开启鼠标缩放和平移漫游 is_rotate_label=False, # 是否旋转标签,默认不旋转 layout='circular', # 图的布局, 'circular' 采用环形布局, 'force' 采用力引导布局 label_opts=opts.series_options.LabelOpts( is_show=True, ), # 标签配置项 linestyle_opts=opts.series_options.LineStyleOpts( curve=0.1)).set_global_opts(title_opts=opts.TitleOpts( title=title)).render(render_name))
def draw_the_whole_graph(): nodes = [opts.GraphNode( name=x, value=G.degree[x], symbol_size=G.degree[x] / 10, ) for x in G.nodes] links = [opts.GraphLink(source=x, target=y, value=G.edges[x, y]['weight'],linestyle_opts=opts.LineStyleOpts(width=G.edges[x, y]['weight']) ) for x, y in G.edges] [math.ceil(G.edges[x, y]['weight'] / max_edge * 10) * 3 for x, y in G.edges] c = ( Graph().add( series_name="", nodes=nodes, links=links, layout='force', is_roam=True, is_focusnode=True, label_opts=opts.LabelOpts(is_show=False), is_draggable=True, # repulsion=100 # linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3, opacity=0.7), ) .set_global_opts(title_opts=opts.TitleOpts(title="Graph with \n authors degrees")) ) return c
def graph_les_miserables(): with open(os.path.join("fixtures", "les-miserables.json"), "r", encoding="utf-8") as f: j = json.load(f) nodes = j["nodes"] links = j["links"] categories = j["categories"] c = (Graph(init_opts=opts.InitOpts(width="1000px", height="600px")).add( "", nodes=nodes, links=links, categories=categories, layout="circular", is_rotate_label=True, linestyle_opts=opts.LineStyleOpts(color="source", curve=0.3), label_opts=opts.LabelOpts(position="right"), ).set_global_opts( title_opts=opts.TitleOpts(title="Graph-Les Miserables"), legend_opts=opts.LegendOpts(orient="vertical", pos_left="2%", pos_top="20%"), )) return c
def graph_2d(open_file) -> Graph: """ 网络拓扑图2D :param open_file: :return: """ title_str = str(open_file).strip().split("/")[-1].split(".")[0] title_str = "Graph<" + title_str + ">" with open(open_file, "r", encoding="utf-8") as f: j = json.load(f) nodes, links, categories = j c = (Graph( init_opts=opts.InitOpts(width="1900px", height="900px", page_title=title_str, theme=ThemeType.DARK)).add( "", nodes, links, categories, repulsion=50, linestyle_opts=opts.LineStyleOpts( curve=0.2), label_opts=opts.LabelOpts(is_show=False), ).set_global_opts( legend_opts=opts.LegendOpts( orient="vertical", pos_left="1%", pos_top="5%", ), title_opts=opts.TitleOpts(title=title_str), )) return c
def graph_with_edge_opts() -> Graph: nodes_data = [ opts.GraphNode(name="结点1", symbol_size=10), opts.GraphNode(name="结点2", symbol_size=20), opts.GraphNode(name="结点3", symbol_size=30), opts.GraphNode(name="结点4", symbol_size=40), opts.GraphNode(name="结点5", symbol_size=50), opts.GraphNode(name="结点6", symbol_size=60), ] links_data = [ opts.GraphLink(source="结点1", target="结点2", value=2), opts.GraphLink(source="结点2", target="结点3", value=3), opts.GraphLink(source="结点3", target="结点4", value=4), opts.GraphLink(source="结点4", target="结点5", value=5), opts.GraphLink(source="结点5", target="结点6", value=6), opts.GraphLink(source="结点6", target="结点1", value=7), ] c = (Graph().add( "", nodes_data, links_data, repulsion=4000, edge_label=opts.LabelOpts( is_show=True, position="middle", formatter="{b} 的数据 {c}", ), ).set_global_opts(title_opts=opts.TitleOpts( title="Graph-GraphNode-GraphLink-WithEdgeLabel"))) return c
def graph_weibo() -> Graph: with open(os.path.join("..\\000LocalData\\echart_example\\", "weibo.json"), "r", encoding="utf-8") as f: j = json.load(f) nodes, links, categories, cont, mid, userl = j as_info_dict, cn_as, categories_dict = read_as_info('..\\000LocalData\\as_compare\\as_core_map_data_integrate20191203.csv') print(as_info_dict) print(categories_dict) as_links_dict = read_as_links('..\\000LocalData\\as_compare\\as_rel_20191203_integrate.txt', cn_as) print(as_links_dict) c = ( Graph(init_opts=opts.InitOpts(width="1920px", height="960px", page_title="Graph-中国AS网络互联关系图", theme=ThemeType.DARK)) .add( "", as_info_dict, as_links_dict, categories_dict, # layout="circular", is_rotate_label=True, gravity=0.2, repulsion=100000, linestyle_opts=opts.LineStyleOpts(width=0.1), label_opts=opts.LabelOpts(is_show=False), ) .set_global_opts( legend_opts=opts.LegendOpts(is_show=False), title_opts=opts.TitleOpts(title="Graph-中国AS网络互联关系图"), ) ) return c