Exemplo n.º 1
0
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
Exemplo n.º 2
0
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")
Exemplo n.º 3
0
def get_type_data(model):
    number = model.number
    categories = [opts.GraphCategory(name='类型')]
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=100,
                       category=0,
                       value=number)
    ]
    links = []
    # 事件总数量
    set_number_node(model, categories, nodes, links)
    # 事件最多社区
    set_max_community_node('Type', model, categories, nodes, links)
    # 类型下所有大类
    maintypes = MainType.objects.filter(type=model)
    name = '大类'
    categories.append(opts.GraphCategory(name=name))
    index = len(categories) - 1
    for maintype in maintypes:
        value = str(maintype)
        number = maintype.number
        if value == str(model):
            value = value + '(问题大类)'
        nodes.append(
            opts.GraphNode(name=value,
                           symbol_size=50,
                           category=index,
                           value=number))
        links.append(
            opts.GraphLink(source=str(model), target=value, value='下属大类'))

    return categories, nodes, links
Exemplo n.º 4
0
def get_maintype_data(model):
    number = model.number
    categories = [opts.GraphCategory(name='大类')]
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=100,
                       category=0,
                       value=number)
    ]
    links = []
    # 事件数量
    set_number_node(model, categories, nodes, links)
    # 所属类型
    set_type_node('MainType', model, categories, nodes, links)
    # 事件最多社区
    set_max_community_node('MainType', model, categories, nodes, links)

    subtypes = SubType.objects.filter(main_type=model)
    name = '小类'
    categories.append(opts.GraphCategory(name=name))
    index = len(categories) - 1
    for subtype in subtypes:
        value = str(subtype)
        sub_number = subtype.number
        if value == str(model) or value == str(model.type):
            value = value + '(问题小类)'
        nodes.append(
            opts.GraphNode(name=value,
                           symbol_size=50,
                           category=index,
                           value=sub_number))
        links.append(
            opts.GraphLink(source=str(model), target=value, value='下属小类'))

    return categories, nodes, links
Exemplo n.º 5
0
def get_district_data(model_name, model):
    categories = [opts.GraphCategory(name='区域')]
    number_d = model.number
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=80,
                       category=0,
                       value=number_d)
    ]
    links = []

    streets = Street.objects.filter(district=model)
    for street in streets:
        name_s = Street.name
        number_s = street.number
        if name_s == 'name' or name_s == 'id':
            continue
        value_s = str(street)
        categories.append(opts.GraphCategory(name='街道'))
        index_s = len(categories) - 1
        nodes.append(
            opts.GraphNode(name=value_s,
                           symbol_size=60,
                           category=index_s,
                           value=number_s))
        links.append(
            opts.GraphLink(source=str(model), target=value_s, value='下属街道'))

    return categories, nodes, links
Exemplo n.º 6
0
def get_street_data(model_name, model):
    categories = [opts.GraphCategory(name='街道')]
    str_number = model.number
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=80,
                       category=0,
                       value=str_number)
    ]
    links = []

    # 街道所属区域
    districts = District.objects.all()
    for district in districts:
        number_c = district.number
        name_c = district.name
        if name_c == 'name' or name_c == 'id':
            continue
        value_c = str(district)
        categories.append(opts.GraphCategory(name='区域'))
        index_c = len(categories) - 1
        nodes.append(
            opts.GraphNode(name=value_c,
                           symbol_size=60,
                           category=index_c,
                           value=number_c))
        links.append(
            opts.GraphLink(source=str(model), target=value_c, value='所属区域'))


# 街道下所有社区及其数量
    communities = Community.objects.filter(street=model)
    for community in communities:
        name_c = Community.name
        number_c = community.number
        # ratio_c = str((round(number_c*100/str_number,2)))+'%'
        if name_c == 'name' or name_c == 'id':
            continue
        value_c = str(community)
        categories.append(opts.GraphCategory(name='社区'))
        index_c = len(categories) - 1
        nodes.append(
            opts.GraphNode(name=value_c,
                           symbol_size=40,
                           category=index_c,
                           value=number_c))
        links.append(
            opts.GraphLink(source=str(model), target=value_c, value='下属社区'))

    return categories, nodes, links
Exemplo n.º 7
0
def get_news_comments_graph_html(id):
    news = get_news(id)
    name = news[4]
    nodes = [
        opts.GraphNode(name, value=news[5], symbol_size=50),
    ]
    comments = get_comments(id)
    links = []
    for comment in comments:
        content = comment[1]
        comment_id = comment[0]
        nodes.append(opts.GraphNode(name=comment_id, value=content, symbol_size=20))
        links.append(opts.GraphLink(source=name, value=content, target=comment_id))
    return make_graph_html(id, nodes, links)
Exemplo n.º 8
0
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))
Exemplo n.º 9
0
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
Exemplo n.º 10
0
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")
Exemplo n.º 11
0
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
Exemplo n.º 12
0
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 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 print_graph(self, init_options, **kwargs):
        nodes_printable = [opts.GraphNode(**n.dict()) for n in self.nodes]
        edges_printable = [opts.GraphLink(**e.dict()) for e in self.edges]

        graph = Graph(init_options)

        graph.add("", nodes_printable, edges_printable, **kwargs)
        graph.render("./Romania.html")
Exemplo n.º 15
0
def set_number_node(model, categories, nodes, links):
    value = str(getattr(model, 'number'))
    categories.append(opts.GraphCategory(name='数量'))
    index = len(categories) - 1
    nodes.append(opts.GraphNode(name=value, symbol_size=50, category=index))
    links.append(opts.GraphLink(source=str(model), target=value,
                                value='事件总数量'))

    return 0
Exemplo n.º 16
0
def graph_with_opts() -> Graph:
    nodes = [
        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),
    ]
    links = [
        opts.GraphLink(source="结点1", target="结点2"),
        opts.GraphLink(source="结点2", target="结点3"),
        opts.GraphLink(source="结点3", target="结点4"),
        opts.GraphLink(source="结点4", target="结点5"),
        opts.GraphLink(source="结点5", target="结点1"),
    ]
    c = (Graph().add("", nodes, links, repulsion=4000).set_global_opts(
        title_opts=opts.TitleOpts(title="Graph-GraphNode-GraphLink")))
    return c
Exemplo n.º 17
0
def get_disposeunit_data(model_name, model):
    number_dis = str(model.number)
    categories = [opts.GraphCategory(name='执行部门')]
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=100,
                       category=0,
                       value=number_dis)
    ]
    links = []

    id = DisposeUnit.objects.filter(name=str(model)).values("id")[0]['id']
    dis_model = DisposeUnit.objects.filter(id=id)[0]

    try:
        # 事件总数
        node_name = str(dis_model.number)
        print(node_name)
        cate_name = '数量'
        link_name = '事件总数'
        source_node = str(dis_model)

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)

        # 完成事件百分比
        is_achieve_count = Event.objects.filter(
            dispose_unit=id).values('achieve').annotate(
                count=Count('achieve')).values('achieve',
                                               'count').order_by('-count')
        is_achieve_count = list(is_achieve_count)
        print(is_achieve_count)
        y = is_achieve_count[0]['count']
        n = is_achieve_count[1]['count']
        percent = round(y * 100 / (y + n), 2)

        node_name = str(percent) + '%'
        cate_name = '百分比'
        link_name = '完成事件百分比'

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)

        # 部门编号
        aid = dis_model.aID

        node_name = str(aid)
        cate_name = '编号'
        link_name = '部门编号'

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)

    except Exception as e:
        print(e)

    return categories, nodes, links
Exemplo n.º 18
0
def get_achive_data(model_name, model):
    events = model.event.get_queryset()
    ratio = '{:.2f}%'.format(model.number / Event.objects.count() * 100)
    unit_list = {}

    for event in events:
        unit = event.dispose_unit.name
        if unit in unit_list:
            unit_list[unit] += 1
        else:
            unit_list.update({unit: 1})

    number_max = 0
    for key in unit_list:
        if unit_list[key] > number_max:
            unit = key
            number_max = unit_list[key]

    categories = [
        opts.GraphCategory(name="执行情况"),
        opts.GraphCategory(name="数量"),
        opts.GraphCategory(name="处置部门"),
        opts.GraphCategory(name="百分比"),
    ]

    nodes = [
        opts.GraphNode(name=str(model.name), symbol_size=80, category=0),
        opts.GraphNode(name=str(model.number), symbol_size=50, category=1),
        opts.GraphNode(name=unit, symbol_size=50, category=2),
        opts.GraphNode(name=ratio, symbol_size=50, category=3),
    ]

    links = [
        opts.GraphLink(source=str(model.name),
                       target=str(model.number),
                       value="事件数量"),
        opts.GraphLink(source=str(model.name),
                       target=unit,
                       value="最多 " + str(model.name) + " 处置机构"),
        opts.GraphLink(source=str(model.name), target=ratio, value="事件占比"),
    ]
    return categories, nodes, links
Exemplo n.º 19
0
def get_source_data(model_name, model):
    events = model.event.get_queryset()
    # 对应性质
    property_list = {}
    for event in events:
        proper = event.property.name
        if proper in property_list.keys():
            property_list[proper] += 1
        else:
            property_list.update({proper: 1})


# 占事件总数百分比
    ratio = '{:.2f}%'.format(model.number / Event.objects.count() * 100)
    number_max = 0
    for key in property_list:
        if property_list[key] > number_max:
            proper = key
            number_max = property_list[key]

    categories = [
        opts.GraphCategory(name="来源"),
        opts.GraphCategory(name="数量"),
        opts.GraphCategory(name="性质"),
        opts.GraphCategory(name="百分比"),
    ]
    nodes = [
        opts.GraphNode(name=str(model), symbol_size=80, category=0),
        opts.GraphNode(name=str(model.number), symbol_size=50, category=1),
        opts.GraphNode(name=proper, symbol_size=50, category=2),
        opts.GraphNode(name=ratio, symbol_size=50, category=3),
    ]

    links = [
        opts.GraphLink(source=str(model),
                       target=str(model.number),
                       value="事件总数量"),
        opts.GraphLink(source=str(model), target=proper, value="对应性质"),
        opts.GraphLink(source=str(model), target=ratio, value="占事件总数百分比"),
    ]

    return categories, nodes, links
Exemplo n.º 20
0
def get_keyword_news_graph_html(keyword):
    news = search_news(keyword)
    nodes = []
    links = []
    exist_ids = []
    for n in news:
        name = n[4]
        id = n[0]
        if name not in exist_ids:
            nodes.append(opts.GraphNode(name, value=n[5], symbol_size=50))
            exist_ids.append(name)
        comments = get_comments(id)
        for comment in comments:
            content = comment[1]
            comment_id = comment[0]
            if comment_id not in exist_ids:
                nodes.append(opts.GraphNode(name=comment_id, value=content, symbol_size=20))
                exist_ids.append(comment_id)
            links.append(opts.GraphLink(source=name, value=content, target=comment_id))
    return make_graph_html(keyword, nodes, links)
Exemplo n.º 21
0
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
Exemplo n.º 22
0
Arquivo: demo.py Projeto: Hellohyy/ZHY
def relation():
    nodes = [
        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),
    ]
    links = [
        opts.GraphLink(source="结点1", target="结点2"),
        opts.GraphLink(source="结点2", target="结点3"),
        opts.GraphLink(source="结点3", target="结点4"),
        opts.GraphLink(source="结点4", target="结点5"),
        opts.GraphLink(source="结点5", target="结点1"),
    ]
    c = (
        Graph()
            .add("", nodes, links, repulsion=4000)
            .set_global_opts(title_opts=opts.TitleOpts(title="学生关系图"))
    )
    c.render("templates/relation.html")
    return render_template("relation.html")
Exemplo n.º 23
0
def generate_nodes_links():
    nodes_data1 = []  # 节点数据
    for i in np.arange(len(influence_man_nodes)):
        nodes_data1.append(opts.GraphNode(name=influence_man_nodes["person"][i],
                                          symbol_size=30 if int(influence_man_nodes["influence_value"][i]) > 50 else 10,
                                          category=int(influence_man_nodes["main_genre"][i])
                                          ))
        # nodes_data1.append({"name": influence_man_nodes["person"][i],
        #                     # "symbol_size": 10,
        #                     "category": int(influence_man_nodes["main_genre"][i])
        #                     })
    links_data1 = []  # 关系数据 边数据
    for i in np.arange(len(influence_man_data)):
        links_data1.append(opts.GraphLink(source=influence_man_data["follower_name"][i],
                                          target=influence_man_data["influencer_name"][i],
                                          value=2))
    return nodes_data1, links_data1
Exemplo n.º 24
0
	def exportECharts(self, nodes, relationships):
		# 总频次,用于数据的归一化
		total = sum(list(map(lambda x:x[1], nodes.items())))

		# 输出节点
		nodes_data = []
		for name, freq in nodes.items():
			nodes_data.append(opts.GraphNode(
				name = name, 
				symbol_size = round(freq / total * 100, 2), 
				value = freq,
			)),

		# 输出边
		links_data = []
		for name, edges in relationships.items():
				for v, w in edges.items():
					if w > 0:
						links_data.append(opts.GraphLink(source = v, target = w, value = w))

		# 绘制Graph
		c = (
			Graph()
			.add(
				"",
				nodes_data,
				links_data,
				gravity = 0.2,
				repulsion = 8000,
				is_draggable = True,
				symbol = 'circle',
				linestyle_opts = opts.LineStyleOpts(
					curve = 0.3, width = 0.5, opacity = 0.7
				),
				edge_label = opts.LabelOpts(
					is_show = False, position = "middle", formatter = "{b}->{c}"
				),
			)
			.set_global_opts(
				title_opts = opts.TitleOpts(title="半泽直树原著小说人物关系抽取")
			)
			.render("./docs/半泽直树原著小说人物关系抽取.html")
		)
Exemplo n.º 25
0
def set_max_community_node(model_name, model, categories, nodes, links):
    max_num = 0
    communities = Community.objects.all()
    if model_name == 'MainType':
        subtypes = SubType.objects.filter(main_type=model)
        for community in communities:
            events = Event.objects.filter(sub_type__in=subtypes,
                                          community=community)
            now_num = len(events)
            if now_num > max_num:
                max_num = now_num
                max_community = community
    if model_name == 'SubType':
        for community in communities:
            events = Event.objects.filter(sub_type=model, community=community)
            now_num = len(events)
            if now_num > max_num:
                max_num = now_num
                max_community = community
    if model_name == 'Type':
        maintypes = MainType.objects.filter(type=model)
        subtypes = SubType.objects.filter(main_type__in=maintypes)
        for community in communities:
            events = Event.objects.filter(sub_type__in=subtypes,
                                          community=community)
            now_num = len(events)
            if now_num > max_num:
                max_num = now_num
                max_community = community
    name = '社区'
    categories.append(opts.GraphCategory(name=name))
    index = len(categories) - 1
    value = str(max_community)
    nodes.append(
        opts.GraphNode(name=value,
                       value=str(max_num),
                       symbol_size=50,
                       category=index))
    links.append(
        opts.GraphLink(source=str(model), target=value, value='发生最多的社区'))
Exemplo n.º 26
0
def create_node(source_node,
                categories,
                cate_name,
                nodes,
                node_name,
                links,
                link_name,
                node_value='-'):
    categories.append(opts.GraphCategory(cate_name))
    print(cate_name)
    length = len(categories) - 1
    nodes.append(
        opts.GraphNode(name=node_name,
                       value=node_value,
                       symbol_size=50,
                       category=length))
    print(node_name)
    links.append(
        opts.GraphLink(source=source_node, target=node_name, value=link_name))
    print(link_name)

    return 0
Exemplo n.º 27
0
def set_type_node(model_name, model, categories, nodes, links):
    if model_name == 'SubType':
        sub_model = model
        model = model.main_type

    thetype = model.type
    type_number = model.type.number
    name = '类型'
    categories.append(opts.GraphCategory(name=name))
    index = len(categories) - 1
    value = str(thetype)
    if (model_name == 'SubType'
            and value == str(sub_model)) or value == str(model):
        value = value + '(问题类型)'
    nodes.append(
        opts.GraphNode(name=value,
                       symbol_size=50,
                       category=index,
                       value=type_number))
    links.append(opts.GraphLink(source=str(model), target=value, value='类型'))

    return 0
Exemplo n.º 28
0
def get_graph_view(all_warehouse_name, all_warehouse_line) -> Graph:
    nodes_data = [
        opts.GraphNode(name=warehouse_id.name, symbol_size=10)
        for warehouse_id in all_warehouse_name
    ]
    links_data = [
        opts.GraphLink(source=x[0], target=x[1], value=x[2])
        for x in all_warehouse_line
    ]

    c = (Graph().add(
        "",
        nodes_data,
        links_data,
        repulsion=8000,
        edge_label=opts.LabelOpts(
            is_show=True,
            position="middle",
            formatter="{b}",
        ),
        edge_symbol='arrow',
    ).set_global_opts(title_opts=opts.TitleOpts(title="Graph-网络")))
    return c.dump_options_with_quotes()
Exemplo n.º 29
0
def pre_graph_data(df):
    #筛选数据&去除全为空值的行
    volunteer_cols = [
        'volunteer_1', 'volunteer_2', 'volunteer_3', 'volunteer_4',
        'volunteer_5'
    ]
    graph_data = df[['school'] + volunteer_cols]
    notna_idx = graph_data[volunteer_cols].dropna(how='all').index
    graph_data = graph_data.loc[notna_idx]

    #高中名称添加(高)
    def add_high_school(x):
        try:
            return (x + '(高)')
        except:
            return x

    graph_data[volunteer_cols] = graph_data[volunteer_cols].applymap(
        add_high_school)

    nodes = []
    #初中学校
    for school_name in graph_data['school'].unique():
        count = (graph_data['school'] == school_name).sum()
        nodes.append(
            opts.GraphNode(name=school_name,
                           symbol_size=int(count),
                           value=int(count),
                           category='初中'))

    #第一批次学校
    first_batch = (graph_data['volunteer_1'].append(
        graph_data['volunteer_2'])).dropna()
    for school_name in first_batch.unique():
        count = (first_batch == school_name).sum()
        nodes.append(
            opts.GraphNode(name=school_name,
                           symbol_size=int(count),
                           value=int(count),
                           category='第一批次'))

    #第二批次学校
    second_batch = (graph_data['volunteer_3'].append(
        graph_data['volunteer_4']).append(graph_data['volunteer_5'])).dropna()
    for school_name in second_batch.unique():
        count = (second_batch == school_name).sum()
        nodes.append(
            opts.GraphNode(name=school_name,
                           symbol_size=int(count),
                           value=int(count),
                           category='第二批次'))

    def data2links(pivot_data, color):
        '''
        将分志愿计数的dataframe处理成links
        '''
        links = []
        for idx in pivot_data.index:
            for col in pivot_data.columns:
                if not np.isnan(pivot_data.loc[idx, col]):
                    links.append(
                        opts.GraphLink(source=idx,
                                       target=col,
                                       value=int(pivot_data.loc[idx, col]),
                                       linestyle_opts=opts.LineStyleOpts(
                                           width=int(pivot_data.loc[idx, col]),
                                           color=color,
                                           curve=0.2)))
        return links

    #各志愿对应的线条颜色
    colors = ['#FF8947', '#41E89D', '#FF8947', '#41E89D', '#557EFF']
    links = []
    for volunteer, color in list(zip(volunteer_cols, colors)):
        pivot_data = graph_data.pivot_table(index='school',
                                            columns=volunteer,
                                            aggfunc='size')
        link = data2links(pivot_data, color)
        links += link
    #Categories
    categories = [
        opts.GraphCategory(name='初中'),
        opts.GraphCategory(name='第一批次'),
        opts.GraphCategory(name='第二批次')
    ]
    return nodes, links, categories
from pyecharts import options as opts
from pyecharts.charts import 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")).render(
        "graph_with_edge_options.html"))