Esempio n. 1
0
def test_graph_force_layout():
    links = []
    for i in nodes:
        for j in nodes:
            links.append({"source": i.get('name'), "target": j.get('name')})
    graph = Graph("关系图-力引导布局示例")
    graph.add("", nodes, links, repulsion=8000, line_color='#aaa')
    graph.render()
Esempio n. 2
0
def test_graph_circular_layout():
    links = []
    for i in nodes:
        for j in nodes:
            links.append({"source": i.get('name'), "target": j.get('name')})
    graph = Graph("关系图-环形布局示例")
    graph.add("", nodes, links, is_label_show=True, graph_repulsion=8000,
              graph_layout='circular', label_text_color=None)
    graph.render()
Esempio n. 3
0
def test_graph_official_data():
    import json
    if PY2:
        import codecs
        with codecs.open(os.path.join("..", "json", "weibo.json"), "rb") as f:
            j = json.load(f)
    else:
        with open(os.path.join("..", "json", "weibo.json"),
                  "r", encoding="utf-8") as f:
            j = json.load(f)
    nodes, links, categories, cont, mid, _ = j
    graph = Graph("微博转发关系图", width=1200, height=600)
    graph.add("", nodes, links, categories, label_pos="right",
              graph_repulsion=50, is_legend_show=False,
              line_curve=0.2, label_text_color=None)
    graph.render()
Esempio n. 4
0
    
#print j 
#print len(j)
nodes, links, categories, cont, mid, _ = j

print nodes
nodes_list = []

for m in nodes:
    #print m
    for n in m:
        pass
        #print n
    #print m['name']
    nodes_list.append({'name':m['name'], 'symbolSize':m['symbolSize'], 
                       'category':m['category']})
#print nodes_list    
print categories           
'''
print len(categories)
for x in categories:
    print 'x',x
    for y in x:
        print '%s---%s' %(y, x[y])
        
'''        
graph = Graph("微博转发关系图", width=1200, height=600)
graph.add("", nodes_list, links, categories, label_pos="right",
              graph_repulsion=50, is_legend_show=False,
              line_curve=0.2, label_text_color=None, is_label_show=True)
graph.render('graph3.html')        
Esempio n. 5
0
u2n = {}
n2u = {}
for item in user_set:
    u2n[item] = i
    n2u[i] = item
    i += 1

for i in range(5000):
    for j in edges[i][1]:
        if j not in user_set:
            continue
        links.append({"source": j, "target": edges[i][0]})

cati = ['#a6c84c', '#ffa022']

graph = Graph("豆瓣关注关系图", width=1600, height=900)
graph.add("",
          nodes,
          links,
          cat2,
          label_pos="right",
          graph_layout='force',
          graph_repulsion=500,
          is_legend_show=False,
          line_curve=0.2,
          label_text_color=None)
graph.render()

# graph = Graph("关系图-力引导布局示例")
# graph.add("", nodes, links, repulsion=50000)
# graph.render()
Esempio n. 6
0
def create_charts():
    page = Page()

    style = Style(width=1100, height=600)

    df = pd.read_csv('./处置部门关联规则.csv')

    x_list = list(df['lhs'].values)
    y_list = list(df['rhs'].values)
    sup = list(df['sup_lhs'])
    conf = list(df['conf'])
    nodes = []
    links = []
    all_list = []
    all_list.extend(x_list)
    all_list.extend(y_list)
    all_list = list(set(all_list))
    for i in range(len(all_list)):
        nodes.append({
            "name": all_list[i],
            "symbolSize": 10,
            "label": {
                "normal": {
                    "show": "True"
                }
            }
        })

    for j in range(len(x_list)):
        links.append({"source": x_list[j], "target": y_list[j]})

    # print(nodes)
    # print(links)
    chart = Graph("关联规则", **style.init_style)
    chart.add("",
              nodes,
              links,
              label_pos="right",
              graph_repulsion=1000,
              is_legend_show=False,
              line_curve=0.2,
              label_text_color=None)
    page.add(chart)

    comm_name = [
        '竹坑社区', '沙田社区', '龙田社区', '秀新社区', '金沙社区', '碧岭社区', '老坑社区', '和平社区', '六和社区',
        '六联社区', '坪山社区'
    ]
    nodes = []
    links = []
    categories = []
    for name in comm_name:
        # print(name)
        df = pd.read_csv('./' + name + '.csv')
        x_list = list(df['lhs'].values)
        y_list = list(df['rhs'].values)
        all_list = []
        all_list.extend(x_list)
        all_list.extend(y_list)
        all_list = list(set(all_list))
        for i in range(len(all_list)):
            # print(all_list[i])
            nodes.append({
                "name": name + all_list[i],
                "symbolSize": 10,
                "draggable": "False",
                "category": name,
                "label": {
                    "normal": {
                        "show": "True"
                    }
                }
            })
        categories.append({"name": name})

        for j in range(len(x_list)):
            links.append({
                "source": name + x_list[j],
                "target": name + y_list[j]
            })

    chart = Graph("", **style.init_style)
    chart.add("",
              nodes,
              links,
              categories,
              label_pos="right",
              graph_repulsion=1000,
              is_legend_show=True,
              line_curve=0.2,
              label_text_color=None)
    page.add(chart)

    return page
Esempio n. 7
0
         {"name": str(location_id[6]), "symbolSize": source_freq[location_id[6]]/50},
         {"name": str(location_id[7]), "symbolSize": source_freq[location_id[7]]/50},
         {"name": str(location_id[8]), "symbolSize": source_freq[location_id[8]]/50},
         {"name": str(location_id[9]), "symbolSize": source_freq[location_id[9]]/50}]

links = []
# for i in nodes:
#     for j in nodes:
#         links.append({"source": i.get('name'), "target": j.get('name')})

for i in range(10):
    search = df.loc[df['sourceid'] == location_id[i], ['dstid', 'month', 'mean_travel_time']]
    ssearch = search.loc[search['month'] == month, ['dstid', 'mean_travel_time']]
    for j in range(10):
        if ssearch[(ssearch.dstid == location_id[j])].index.tolist():
            value = ssearch.loc[ssearch['dstid'] == location_id[j], ['mean_travel_time']]
            value = list(value['mean_travel_time'])
            links.append({"source": str(location_id[i]), "target": str(location_id[j]), "value": str(value[0]) + ' sec'})
""""value": value[0]"""
graph = Graph("")
graph.add("",
          nodes,
          links,
          is_label_show=True,
          graph_layout="circular",
          label_text_color=None,
          graph_edge_symbol="arrow")
graph.render()


Esempio n. 8
0
    def show(self):
        '''
        将添加的节点以及链接展示出来
        Show the nodes and links added before.

        Returns
        ---
        pyechats Graph object
            This will draw the graph oject.
        '''
        # 处理link节点,删除不在nodes中的节点
        _link_nodes = set([x['source'] for x in self.links]) | set(
            [x['target'] for x in self.links])
        _nodes = self.all_nodes
        _del_link_nodes = _link_nodes - set(_nodes)
        self.links = list(
            filter(
                lambda x: x['source'] not in _del_link_nodes and x['target']
                not in _del_link_nodes, self.links))

        #set the connected nodes to head
        linked_nodes = [x["source"] for x in self.links]
        linked_nodes.extend([x["target"] for x in self.links])
        for cat in self.nodes.keys():
            if self.nodes[cat] == []:
                pass
            elif len(self.nodes[cat]) < 10:
                pass
            else:
                connect_nodes = list(set(self.nodes[cat]) & set(linked_nodes))
                other_nodes = list(set(self.nodes[cat]) - set(connect_nodes))
                connect_nodes.extend(other_nodes)
                self.nodes[cat] = connect_nodes

        graph = Graph(self.title, self.subtitle, height=len(_nodes) * 25)
        nodes = []
        nodes_pos = [0, 0]
        symbol_width = max(map(
            len, self.all_nodes)) * 10  # get the max charactor length
        symbol_width = min(max(symbol_width, 80), 200)  # min is 80, max is 200
        for cat_id, cats in enumerate(self.nodes.keys()):
            for node_id, cat_nodes in enumerate(self.nodes[cats]):
                self.categories.append(cats)
                nodes_pos = [cat_id * 300, node_id * 20]
                nodes.append({
                    "name": cat_nodes,
                    "x": nodes_pos[0],
                    "y": nodes_pos[1],
                    'symbolSize': [symbol_width, 20],
                    "symbol": 'rect',
                    "category": (cats % 20),
                    "graph_repulsion": 1000000
                })

        graph.add("",
                  nodes,
                  self.links,
                  categories=self.categories,
                  **self.node_style)

        # graph.render() I do not know why this API is not work in my environment.
        return graph
Esempio n. 9
0
         {"name": "4", "symbolSize": 4},
         {"name": "5", "symbolSize": 5},
         {"name": "6", "symbolSize": 4},
         {"name": "7", "symbolSize": 13},
         {"name": "8", "symbolSize": 20}]
links = []
for i in nodes:
    for j in nodes:
        links.append({"source": i.get('name'), "target": j.get('name')})
        
link_1 = [{'source': '1', 'target':'5'}, {'source': '1', 'target':'7'},{'source': '3', 'target':'6'}]
link_2 = [{'source': '2', 'target':'4'}, {'source': '4', 'target':'8'},{'source': '3', 'target':'7'}]
link_3 = [{'source': '1', 'target':'2'}, {'source': '2', 'target':'3'},{'source': '7', 'target':'8'}]
links = link_1 + link_2 + link_3
        
graph = Graph("关系图-力引导布局示例")
graph.add("", nodes, links, repulsion=80, graph_gravity=0.1) # graph_gravity 代表相心力 1最大。 repulsion 代表节点斥力 无上限
graph.render()

nodes = [{"name": "1", "symbolSize": 10},
         {"name": "2", "symbolSize": 20},
         {"name": "3", "symbolSize": 13},
         {"name": "4", "symbolSize": 4},
         {"name": "5", "symbolSize": 5},
         {"name": "6", "symbolSize": 4},
         {"name": "7", "symbolSize": 13},
         {"name": "8", "symbolSize": 20}]
        
link_1 = [{'source': '1', 'target':'5'}, {'source': '1', 'target':'7'},{'source': '3', 'target':'6'}]
link_2 = [{'source': '2', 'target':'4'}, {'source': '4', 'target':'8'},{'source': '3', 'target':'7'}]
link_3 = [{'source': '1', 'target':'2'}, {'source': '2', 'target':'3'},{'source': '7', 'target':'8'}]
Esempio n. 10
0
graph_cited = Graph(("InterDiscipline Cited Relationship_%s" % num_top_citations), **style.init_style)
graph_cited.add(
    "",
    nodes,
    links,
    is_label_show=True,
    graph_layout="circular",
#    line_width =2,
    label_text_color=None,
#    line_curve =  0.1,
    graph_edge_symbol=  [None,"arrow"]
)
graph_cited.render("render_cited.html")
'''
graph = Graph(("InterDiscipline Citing Relationship_%s" % num_top_citations),
              **style.init_style)
graph.add(
    "",
    nodes,
    links,
    is_label_show=True,
    graph_layout="circular",
    #    line_width =2,
    label_text_color=None,
    #    line_curve =  0.1,
    graph_edge_symbol=[None, "arrow"])
graph.render()

#---------Paper Distribution-------------------#
bar = Bar('Paper Distribution', '')
kwargs = dict(name='Distribution of Papers',
from pyecharts import Graph
import pandas as pd

sim_frame = pd.read_csv('./data/philosophy.csv', index_col=0, encoding='utf8')
names = sim_frame.index
sim_frame = sim_frame ** 0.25

graph = Graph('哲♂学关系图', width=1000, height=1000)
nodes = [{'name': name, 'symbolSize': 30, 'value': 1} for name in names]
links = [{
    'source': i,
    'target': j,
    'value': sim_frame.loc[i, j]
} for i in names for j in names if i < j]
graph.add(
    '', nodes, links,
    is_focusnode=True,
    is_roam=True,
    is_rotatelabel=False,
    layout="force",
    graph_edge_length=list(range(100, 601, 100)),
    graph_gravity=0.1,
    graph_repulsion=8000,
    is_label_show=True,
    is_legend_show=True,
    line_curve=0,
)
graph.render('./data/philosophy.html')

Esempio n. 12
0
# 读取文件
def load_pickle(dir):
    pkl_file = open(dir, 'rb')
    ego = pickle.load(pkl_file)
    pkl_file.close()
    return ego


dic_dir = "coo_author.pkl"
author = "Leandro Tortosa"
ego_dic = load_pickle(dic_dir)

nodes = [{'name': author, 'symbolSize': 10}]
links = []
for item in ego_dic[author].items():
    nodes.append({'name': item[0], 'symbolSize': item[1]})
    links.append({"source": author, "target": item[0]})

graph = Graph("Ego-network of %s" % author)
graph.add("",
          nodes,
          links,
          is_label_show=True,
          label_text_color='k',
          is_legend_show=True,
          repulsion=8000,
          is_focusnode=True,
          is_rotatelabel=True,
          is_roam=True)
graph.render()
Esempio n. 13
0
        nodes_p.append(author)

name = [
    "neural networks", "large-scale", "convolutional neural network",
    "deep neural networks", "results show that", "experiments show that",
    "generative adversarial networks", "visual question answering",
    "neural networks cnns", "deep convolutional neural",
    "experimental results show", "Learning Deep", "Glimpse Clouds",
    "Deep Q-Learning"
]
value = [497, 200, 240, 70, 56, 45, 43, 39, 36, 33, 32, 100, 50, 30]

wordcloud = WordCloud("CVPR热词高频词")
wordcloud.add("", name, value, word_size_range=[20, 100])

graph = Graph("CVPR全部作者图谱", width=800, height=800)
graph.add(
    "",
    nodes,
    [],
    is_label_show=True,
    graph_repulsion=50,
    is_legend_show=False,
    graph_edge_length=100,
    label_text_color=None,
)
graph2 = Graph("CVPR活跃作者关系图", width=800, height=800)

graph2.add(
    "",
    nodes_p,
Esempio n. 14
0
day = datetime.date(2014,3,1)
end = datetime.date(2014,3,31)

conn = MySQLdb.connect(**db_config)
cursor = conn.cursor()
cursor.execute('select distinct day from last_day order by day asc')
days = [x[0] for x in cursor.fetchall()]
cursor.close()
conn.close()

while day<=end:
	if day in days:
		cf = CapitalFlow(account, day)
		mats.append(cf.cf)
	day += datetime.timedelta(1)


# graph
graph = Graph('账户:{0}\t日期:2014年3月'.format(account), width=1000, height=618)
V = [{'name':x, 'symbolSize':28} for x in ['sfe','dce','czce','cffex', 'fund']]
E = []
for mat in mats:
	for i in range(5):
		for j in range(5):
			if mat[i,j]>0:
				E.append({'source':i, 'target':j, 'value':round(mat[i,j]), 
				'lineStyle':{'normal':{'width':min(mat[i,j]/2000+0.8,10)}}})
graph.add('', V, E, graph_repulsion=2000, is_label_show=True, graph_edge_symbol=[None, 'arrow'], graph_edge_symbolsize=28,
		label_text_size=18, label_emphasis_textsize=18, label_emphasis_textcolor='#000', line_color='#00F', line_curve=0.2)
		
graph.render()
Esempio n. 15
0
#定义有向图
g = nx.DiGraph()
edges = []
for i in range(len(df2)):
    edges.append([df2.loc[i, "Source"], df2.loc[i, "Target"]])
# In[3]:
#仅仅是社交网络关系
for i in range(len(df)):
    g.add_node(df.Id[i])
# add edges
for i in range(len(df2)):
    g.add_edge(edges[i][0], edges[i][1])

g_data = json_graph.node_link_data(g)

graph = Graph("豆瓣关注关系图", width=1600, height=900)
graph.add("",
          nodes=g_data['nodes'],
          links=g_data['links'],
          categories=cat2,
          is_legend_show=False,
          line_curve=0.2,
          label_pos="right")
graph.render("relationship.html")

# In[4]:
# 分割社区后
links = []
for i in range(len(df2)):
    links.append({"source": edges[i][0], "target": edges[i][1]})
graph = Graph("豆瓣关注关系图", width=1600, height=900)
            str(link),
            "target":
            str(ol),
            "value":
            int(info[info.link_ID == int(linkDict[str(link)])]
                ['length'].values[0]) +
            (0 if ol == "" else int(
                info[info.link_ID == int(linkDict[ol])]['length'].values[0]))
        })
    for il in inl.split("#"):
        links.append({
            "source":
            str(il),
            "target":
            str(link),
            "value":
            int(info[info.link_ID == int(linkDict[str(link)])]
                ['length'].values[0]) +
            (0 if il == "" else int(
                info[info.link_ID == int(linkDict[il])]['length'].values[0]))
        })
graph = Graph("road_graph", width=1600, height=800)
graph.add("",
          nodes,
          links,
          is_label_show=True,
          repulsion=1000,
          label_text_color=None,
          gravity=0.001)
# # graph.show_config()
graph.render()
Esempio n. 17
0
def drawGraphRelation2():
    from pyecharts import Graph

    nodes = [{
        "name": "rule1",
        "symbolSize": 20
    }, {
        "name": "rule2",
        "symbolSize": 20
    }, {
        "name": "rule3",
        "symbolSize": 20
    }, {
        "name": "rule4",
        "symbolSize": 20
    }, {
        "name": "rule5",
        "symbolSize": 20
    }, {
        "name": "rule6",
        "symbolSize": 20
    }, {
        "name": "rule7",
        "symbolSize": 20
    }, {
        "name": "rule8",
        "symbolSize": 20
    }, {
        "name": "rule9",
        "symbolSize": 20
    }, {
        "name": "rule1_1",
        "symbolSize": 10
    }, {
        "name": "rule1_2",
        "symbolSize": 10
    }, {
        "name": "rule1_3",
        "symbolSize": 10
    }, {
        "name": "rule2_1",
        "symbolSize": 10
    }, {
        "name": "rule2_2",
        "symbolSize": 10
    }, {
        "name": "rule2_1_1",
        "symbolSize": 10
    }, {
        "name": "rule2_1_2",
        "symbolSize": 10
    }, {
        "name": "rule2_1_3",
        "symbolSize": 10
    }, {
        "name": "rule2_2_1",
        "symbolSize": 10
    }, {
        "name": "rule3_1",
        "symbolSize": 10
    }, {
        "name": "rule3_2",
        "symbolSize": 10
    }, {
        "name": "rule0",
        "symbolSize": 30
    }]
    links = []

    links.append({"source": "rule0", "target": "rule1"})
    links.append({"source": "rule0", "target": "rule2"})
    links.append({"source": "rule0", "target": "rule3"})
    links.append({"source": "rule0", "target": "rule4"})
    links.append({"source": "rule0", "target": "rule5"})
    links.append({"source": "rule0", "target": "rule6"})
    links.append({"source": "rule0", "target": "rule7"})
    links.append({"source": "rule0", "target": "rule8"})
    links.append({"source": "rule0", "target": "rule9"})
    links.append({"source": "rule1", "target": "rule1_1"})
    links.append({"source": "rule1", "target": "rule1_2"})
    links.append({"source": "rule1", "target": "rule1_3"})
    links.append({"source": "rule2", "target": "rule2_1"})
    links.append({"source": "rule2", "target": "rule2_2"})
    links.append({"source": "rule2_1", "target": "rule2_1_1"})
    links.append({"source": "rule2_1", "target": "rule2_1_2"})

    links.append({"source": "rule2_1", "target": "rule2_2_1"})
    links.append({"source": "rule3", "target": "rule3_1"})
    links.append({"source": "rule3", "target": "rule3_2"})

    graph = Graph("Demo of Pyechart - Rule relationship")
    graph.add(
        "",
        nodes,
        links,
        is_label_show=True,
        #graph_repulsion=8000,
        graph_repulsion=80000,
        line_curve=0.2,
        graph_layout="circular",
        label_text_color=None,
    )
    graph.render()
Esempio n. 18
0
def create_Graph(data):
    # 如果是进入主页则展示所有企业的关系图
    if data == 'is_begin_index':
        spo = pd.read_excel(r'c2c.xlsx')
        company = pd.read_excel(r'company.xlsx')

        # 将节点间的关系存入links
        links = []
        for i in range(spo.shape[0]):
            links.append({
                'source': spo.iloc[i, 1],
                'target': spo.iloc[i, 3],
                'category': 1,
                "value": spo.iloc[i, 2],
                'label': {
                    'normal': {
                        'show': True,
                        'formatter': "{c}"
                    }
                }
            })

        # 将节点存入nodes
        nodes = []
        for i in range(company.shape[0]):
            nodes.append({
                'name': company.iloc[i, 1],
                'category': 1,
                'symbolSize': 10,
                'draggable': True,
                'symbol': 'square'
            })

        # 画图
        graph = Graph('', width=1200, height=600)
        graph.add('',
                  nodes,
                  links,
                  categories=['个人', '企业'],
                  label_pos='right',
                  graph_repulsion=200,
                  is_legend_show=True,
                  line_curve=0,
                  label_text_color=None,
                  is_label_show=True,
                  is_symbol_show=True,
                  graph_edge_symbol=[None, 'arrow'])
        # 监听鼠标点击事件
        graph.on(events.MOUSE_CLICK, on_click)

    # 如果有请求搜索的内容则进入下面的代码块
    else:
        item = str(data)
        spo = pd.read_excel(r'final_spo.xlsx')
        company = pd.read_excel(r'company.xlsx')

        # 以正则表达式匹配人名,有些人名后有数字,以此来分辨是否为同一个人
        object_search = spo[spo['object'].str.contains('%s[1-9]?$' % item)]
        object2_search = spo[spo['object_2'].str.contains('%s[1-9]?$' % item)]

        links = []
        # 如果没找到搜索内容则返回404
        if object_search.empty and object2_search.empty:
            return '404'
        # 找到了则进行如下处理
        else:
            # 由于数据库的布局,公司名称一定出现在object_2这一列,所以如果object列搜索结果为空,而object_2搜索不为空,则说明搜索的一定为企业,则把属于该企业的所有人都显示出
            if object_search.empty:
                # 找出该企业的所有人
                grouped_spo = spo.groupby('company')
                for name, group in grouped_spo:
                    if name == object2_search.iloc[0, 2]:
                        result = group

                # 存入结点间的关系
                for i in range(result.shape[0]):
                    links.append({
                        'source': result.iloc[i, 0],
                        'target': result.iloc[i, 2],
                        'category': 1,
                        "value": result.iloc[i, 1],
                        'label': {
                            'normal': {
                                'show': True,
                                'formatter': "{c}"
                            }
                        }
                    })

                # 存入相关结点
                nodes = []
                person_nodes = result.drop_duplicates('object', keep='first')
                for i in range(person_nodes.shape[0]):
                    nodes.append({
                        'name': person_nodes.iloc[i, 0],
                        'category': 0,
                        'symbolSize': 10,
                        'draggable': True
                    })

                company_nodes = result.drop_duplicates('company', keep='first')
                for i in range(company_nodes.shape[0]):
                    nodes.append({
                        'name': company_nodes.iloc[i, 3],
                        'category': 1,
                        'symbolSize': 20,
                        'draggable': True,
                        'symbol': 'square'
                    })

            # 如果object有搜索结果,则说明搜索内容不是公司,而是人物
            else:
                # 将结点间的关系存入links
                for i in range(object_search.shape[0]):
                    links.append({
                        'source': object_search.iloc[i, 0],
                        'target': object_search.iloc[i, 2],
                        'category': 1,
                        "value": object_search.iloc[i, 1],
                        'label': {
                            'normal': {
                                'show': True,
                                'formatter': "{c}"
                            }
                        }
                    })

                # 搜索出来的是人物的话,把他所属的公司也一并显示出来
                links.append({
                    'source': object_search.iloc[0, 0],
                    'target': object_search.iloc[0, 3],
                    'category': 1,
                    "value": '属于',
                    'label': {
                        'normal': {
                            'show': True,
                            'formatter': "{c}"
                        }
                    }
                })

                for i in range(object2_search.shape[0]):
                    links.append({
                        'source': object2_search.iloc[i, 0],
                        'target': object2_search.iloc[i, 2],
                        'category': 1,
                        "value": object2_search.iloc[i, 1],
                        'label': {
                            'normal': {
                                'show': True,
                                'formatter': "{c}"
                            }
                        }
                    })

                # 将相关结点存入nodes,由于在object和object_2两列搜索,所以要将两列的相关结点都存入,所以要存两遍(此处处理方法并不好,应该有更简单的处理方法和代码形式)
                # 此处存入object搜索结果
                nodes = []

                person_nodes = object_search.drop_duplicates('object',
                                                             keep='first')
                for i in range(person_nodes.shape[0]):
                    nodes.append({
                        'name': person_nodes.iloc[i, 0],
                        'category': 0,
                        'symbolSize': 10,
                        'draggable': True
                    })

                # 这里虽然叫company_nodes,但是可能是公司也可能是人物
                company_nodes = object_search.drop_duplicates('object_2',
                                                              keep='first')
                for i in range(company_nodes.shape[0]):
                    # 在object2中如果是公司的话就用公司的结点大小与形状,如果不是就用个人的
                    if company_nodes.iloc[i, 2] in list(company['company']):
                        nodes.append({
                            'name': company_nodes.iloc[i, 2],
                            'category': 1,
                            'symbolSize': 20,
                            'draggable': True,
                            'symbol': 'square'
                        })
                    else:
                        nodes.append({
                            'name': object_search.iloc[i, 2],
                            'category': 0,
                            'symbolSize': 10,
                            'draggable': True
                        })

                # 如果搜索出来的是人物的话,把公司结点也加入进去,以便显示其公司节点
                nodes.append({
                    'name': company_nodes.iloc[0, 3],
                    'category': 1,
                    'symbolSize': 20,
                    'draggable': True,
                    'symbol': 'square'
                })

                # 此处存入object_2的搜索结果
                person_nodes = object2_search.drop_duplicates('object',
                                                              keep='first')
                for i in range(person_nodes.shape[0]):
                    nodes.append({
                        'name': person_nodes.iloc[i, 0],
                        'category': 0,
                        'symbolSize': 10,
                        'draggable': True
                    })

                company_nodes = object2_search.drop_duplicates('object_2',
                                                               keep='first')
                for i in range(company_nodes.shape[0]):
                    if company_nodes.iloc[i, 2] in list(company['company']):
                        nodes.append({
                            'name': company_nodes.iloc[i, 2],
                            'category': 1,
                            'symbolSize': 20,
                            'draggable': True,
                            'symbol': 'square'
                        })
                    else:
                        nodes.append({
                            'name': company_nodes.iloc[i, 2],
                            'category': 0,
                            'symbolSize': 10,
                            'draggable': True
                        })

                # 一般搜索内容的结点会重复存入一次,所以在此处删除重复结点
                for i in range(len(nodes)):
                    for j in range(i + 1, len(nodes)):
                        if nodes[i]['name'] == nodes[j]['name']:
                            nodes.pop(j)
                            break

        # 画图
        graph = Graph('%s关系图' % item, width=1200, height=600)
        graph.add('',
                  nodes,
                  links,
                  categories=['个人', '企业'],
                  label_pos='right',
                  graph_repulsion=500,
                  is_legend_show=True,
                  line_curve=0,
                  label_text_color=None,
                  is_label_show=True,
                  is_symbol_show=True,
                  graph_edge_symbol=[None, 'arrow'])
        # 监听鼠标点击事件
        graph.on(events.MOUSE_CLICK, on_click)

    return graph
Esempio n. 19
0
                   name=i[7].split('@')[0],
                   category=to_kind,
                   symbolSize=to_size)
        g.add_edge(from_id, to_id)
    # g.add_node(i[6])
    # g.has_node(i[7])

# g = nx.Graph()
# g.add_node('G1', name='Gateway 1')
# g.add_node('N2', name='Node 2')
# g.add_node('N2', name='Node 3')
# g.add_edge('G1', 'N2')
# g.add_edge('G1', 'N3')
g_data = json_graph.node_link_data(g)
# print(g_data)
eg = Graph('Email', width=1500, height=800)
eg.add('people',
       nodes=g_data['nodes'],
       links=g_data['links'],
       categories=[{
           'name': '0'
       }, {
           'name': '1'
       }, {
           'name': '2'
       }, {
           'name': '3'
       }, {
           'name': '4'
       }])
eg.render()
Esempio n. 20
0
    # bar
    bar = Bar("群聊情感分析", title_pos='center')
    item_name_list, item_num_list = emotions_count(emotions)
    bar.add("", item_name_list, item_num_list, title_pos='center', is_label_show=True, xaxis_label_textsize=20,
            yaxis_label_textsize=20)
    page.add(bar)

    # graph
    nodes = [{"name": earlest_time_node, "symbolSize": 30},
             {"name": latest_time_node, "symbolSize": 50},
             {"name": earlest_msg_node, "symbolSize": 30},
             {"name": latest_msg_node, "symbolSize": 50}]
    links = [{"source": nodes[0].get('name'), "target": nodes[2].get('name')},
             {"source": nodes[1].get('name'), "target": nodes[3].get('name')}]

    graph = Graph("爱群关系图", title_pos='center')
    graph.add("", nodes, links, is_label_show=True, graph_repulsion=8000, graph_layout="circular",
              label_text_color=None, label_emphasis_textsize=20)
    page.add(graph)

    # wordcloud
    item_name_list, item_num_list = counter2list(keywords_counter.most_common(100))
    wordcloud = WordCloud("话题排行", title_pos='center', width=800, height=600)
    wordcloud.add("", item_name_list, item_num_list, word_size_range=[12, 72], shape='circle')
    page.add(wordcloud)

    file_path = '/virtualhost/webapp/love/wechat/%s月统计与分析.html' % current_month
    # file_path = './analyse/%s月统计与分析.html' % current_month
    page.render(file_path)
    print('http://loveboyin.cn/wechat/%s月统计与分析.html' % current_month)
Esempio n. 21
0
        doc_this_user = col_user.find_one({'number': int(item)})

        this_user_name = str(doc_this_user['username'])
        if this_user_name == target_user_name:
            continue

        this_user_in_degree = doc_this_user['in_degree']
        this_user_size = in_degree2size(this_user_in_degree)
        this_user_color = color_choose(this_user_in_degree)
        node.append({
            'name': this_user_name,
            'symbolSize': int(this_user_size),
            'itemStyle': {
                'color': this_user_color
            }
        })
        # add the link
        link.append({'source': target_user_name, 'target': this_user_name})

    style = Style(title_color="#fff",
                  title_pos="center",
                  width=2760,
                  height=1440,
                  background_color='#404a59')

    page = Page()
    chart = Graph("Github following二度关系推荐图", **style.init_style)
    chart.add("", node, link)
    page.add(chart)
    page.render()
Esempio n. 22
0
    "symbolSize": 50
}, {
    "name": "结点6",
    "symbolSize": 40
}, {
    "name": "结点7",
    "symbolSize": 30
}, {
    "name": "结点8",
    "symbolSize": 20
}]
links = []
for i in nodes:
    for j in nodes:
        links.append({"source": i.get('name'), "target": j.get('name')})
graph = Graph("关系图-力引导布局示例")
graph.add("", nodes, links, repulsion=8000)
# graph.render("关系图.html")

# In[82]:

# 关系图-环形布局示例

nodes = [{
    "name": "结点1",
    "symbolSize": 10
}, {
    "name": "结点2",
    "symbolSize": 20
}, {
    "name": "结点3",
Esempio n. 23
0
def test_graph():

    # graph_0
    nodes = [{"name": "结点1", "symbolSize": 10},
             {"name": "结点2", "symbolSize": 20},
             {"name": "结点3", "symbolSize": 30},
             {"name": "结点4", "symbolSize": 40},
             {"name": "结点5", "symbolSize": 50},
             {"name": "结点6", "symbolSize": 40},
             {"name": "结点7", "symbolSize": 30},
             {"name": "结点8", "symbolSize": 20}]
    links = []
    for i in nodes:
        for j in nodes:
            links.append({"source": i.get('name'), "target": j.get('name')})
    graph = Graph("关系图-力引导布局示例")
    graph.add("", nodes, links, repulsion=8000)
    graph.show_config()
    graph.render()

    # graph_1
    graph = Graph("关系图-环形布局示例")
    graph.add("", nodes, links, is_label_show=True,
              graph_repulsion=8000, graph_layout='circular', label_text_color=None)
    graph.show_config()
    graph.render()

    # graph_2
    import json
    if PY2:
        import codecs
        with codecs.open(os.path.join("..", "json", "weibo.json"), "rb") as f:
            j = json.load(f)
    else:
        with open(os.path.join("..", "json", "weibo.json"), "r", encoding="utf-8") as f:
            j = json.load(f)
    nodes, links, categories, cont, mid, userl = j
    graph = Graph("微博转发关系图", width=1200, height=600)
    graph.add("", nodes, links, categories, label_pos="right", graph_repulsion=50,
              is_legend_show=False, line_curve=0.2, label_text_color=None)
    graph.show_config()
    graph.render()
Esempio n. 24
0
nodes = [
        {"name": "统计学", "symbolSize": 81},
        {"name": "英语熟练", "symbolSize": 66},
        {"name": "普通话", "symbolSize": 46},
        {"name": "数学与应用数学", "symbolSize": 38},
        {"name": "管理", "symbolSize": 19},
        {"name": "会计学", "symbolSize": 17},
        {"name": "计算机科学与技术", "symbolSize": 17},
        {"name": "信息与计算科学", "symbolSize": 15},
    ]
links = []
for i in nodes:
        for j in nodes:
            links.append({"source": i.get("name"), "target": j.get("name")})

graph = Graph(background_color='#404a59')
graph.use_theme('dark')
graph.add("",nodes,links,
        categories=None, # 结点分类的类目,结点可以指定分类,也可以不指定。
        is_focusnode=True, # 是否在鼠标移到节点上的时候突出显示节点以及节点的边和邻接节点。默认为 True
        is_roam=True,
        is_rotatelabel=True, # 是否旋转标签,默认为 False
        graph_layout="force", # 布局类型,默认force=力引导图,circular=环形布局
        graph_edge_length=300, # 力布局下边的两个节点之间的距离,这个距离也会受 repulsion 影响。默认为 50,TODO 值越大则长度越长
        graph_gravity=0.5, # 点受到的向中心的引力因子。TODO 该值越大节点越往中心点靠拢。默认为 0.2
        graph_repulsion=100, # 节点之间的斥力因子。默认为 50,TODO 值越大则斥力越大
        is_label_show=True,
        line_curve=0.2 # 线的弯曲度
          )
#graph.render(r"D:\BI大屏\关系图.html")
page.add_chart(graph,name="graph") 
Esempio n. 25
0
    "symbolSize": 40
}, {
    "name": "结点5",
    "symbolSize": 50
}, {
    "name": "结点6",
    "symbolSize": 40
}, {
    "name": "结点7",
    "symbolSize": 30
}, {
    "name": "结点8",
    "symbolSize": 20
}]
links = []
for i in nodes:
    for j in nodes:
        links.append({"source": i.get('name'), "target": j.get('name')})

print(links)
print(nodes)
graph = Graph("关系图-环形布局示例")
graph.add("",
          nodes,
          links,
          is_label_show=True,
          repulsion=8000,
          layout='circular',
          label_text_color=None)
graph.show_config()
graph.render(path="./data/02-03关系图.html")
Esempio n. 26
0
# coding=utf8
"""
本示例使用 networkx 库构建复杂、更人性化的的关系图
安装 pip install networkx
参考 https://networkx.github.io/
"""

# from __future__ import unicode_literals

import networkx as nx
from networkx.readwrite import json_graph
from pyecharts import Graph

g = nx.Graph()
g.add_node('G1', name='Gateway 1')
g.add_node('N2', name='Node 2')
g.add_node('N3', name='Node 3')
g.add_edge('G1', 'N2')
g.add_edge('G1', 'N3')
g.add_edge('G1', 'N4')
g.add_edge('N2', 'N5')
g.add_edge('N2', 'N6')
g.add_edge('N5', 'N7')
g_data = json_graph.node_link_data(g)
print(g_data)
eg = Graph('设备最新拓扑图')
eg.add('Devices', nodes=g_data['nodes'], links=g_data['links'])
eg.render()
Esempio n. 27
0
        node_list.append(node)
        #node_time_list.append((int(time)))
#print node_time_list
#读取边
with codecs.open('sans_edge_list.txt', 'r', 'utf-8') as f:
    for each_line in f:
        #print tuple(each_line.split())
        edge_list.append({
            'source': each_line.split()[0],
            'target': each_line.split()[1]
        })

nodelist = []
print node_dict
for i in node_dict:
    nodelist.append({'name': i, 'category': i})
categories = nodelist

print edge_list
graph = Graph("关系图-环形布局示例", width=1200, height=600)
graph.add("",
          nodelist,
          edge_list,
          categories,
          is_label_show=True,
          graph_repulsion=50,
          label_text_color=None,
          line_curve=0.2,
          label_pos="right")
graph.render('graph2.html')
}, {
    "name": "宿州学院",
    "symbolSize": 40
}, {
    "name": "安徽大学",
    "symbolSize": 50
}, {
    "name": "铜陵学院",
    "symbolSize": 40
}, {
    "name": "中国科技大学",
    "symbolSize": 30
}, {
    "name": "安徽理工大学",
    "symbolSize": 20
}]
links = []
for i in nodes:
    for j in nodes:
        links.append({"source": i.get('name'), "target": j.get('name')})
graph = Graph("关系图-环形布局示例")
graph.add("",
          nodes,
          links,
          is_label_show=True,
          repulsion=8000,
          layout='circular',
          label_text_color='#000',
          line_curve=0.05)
graph.show_config()
graph.render(r"Graph(关系图).html")
Esempio n. 29
0
}, {
    "name": "结点2",
    "symbolSize": 20
}, {
    "name": "结点3",
    "symbolSize": 30
}, {
    "name": "结点4",
    "symbolSize": 40
}, {
    "name": "结点5",
    "symbolSize": 50
}, {
    "name": "结点6",
    "symbolSize": 40
}, {
    "name": "结点7",
    "symbolSize": 30
}, {
    "name": "结点8",
    "symbolSize": 20
}]
links = []

for i in nodes:
    for j in nodes:
        links.append({"source": i.get("name"), "target": j.get('name')})

graph = Graph("关系图-力引导布局示例")
graph.add("test", nodes, links, graph_repulsion=8000, is_more_utils=True)
graph.render(path="graph.html")
Esempio n. 30
0
                s_this_color = color_choose(indegree)
                if indegree == 0:
                    size = 3
                else:
                    size = int(math.sqrt(indegree) * 5)
                node.append({
                    'name': str,
                    'symbolSize': int(size),
                    'itemStyle': {
                        'color': s_this_color
                    }
                })
                link.append({'source': target_tag, 'target': str})

    style = Style(title_color="#fff",
                  title_pos="center",
                  width=2760,
                  height=1440,
                  background_color='#404a59')

    print(len(node))
    print(node)
    print(link)
    print(len(link))

    page = Page()
    chart = Graph("二度关系图", **style.init_style)
    chart.add("", node, link)
    page.add(chart)
    page.render()
Esempio n. 31
0
    "symbolSize": 50
}, {
    "name": "结点6",
    "symbolSize": 40
}, {
    "name": "结点7",
    "symbolSize": 30
}, {
    "name": "结点8",
    "symbolSize": 20
}]
links = []
for i in nodes:
    for j in nodes:
        links.append({"source": i.get('name'), "target": j.get('name')})
graph = Graph("关系图-环形布局示例")
graph.add("",
          nodes,
          links,
          is_label_show=True,
          graph_repulsion=800000,
          graph_layout='circular',
          label_text_color=None,
          is_focusnode=True,
          is_roam=True,
          is_rotatelabel=False,
          layout="force",
          edge_length=100,
          gravity=0.001,
          repulsion=100)
graph.render("graph.html")
    "name": "结点3",
    "symbolSize": 30
}, {
    "name": "结点4",
    "symbolSize": 40
}, {
    "name": "结点5",
    "symbolSize": 50
}, {
    "name": "结点6",
    "symbolSize": 40
}, {
    "name": "结点7",
    "symbolSize": 30
}, {
    "name": "结点8",
    "symbolSize": 20
}]
links = []
for i in nodes:
    for j in nodes:
        links.append({"source": i.get('name'), "target": j.get('name')})
graph = Graph("关系图-环形布局示例")
graph.add("",
          nodes,
          links,
          is_label_show=True,
          graph_repulsion=8000,
          graph_layout='circular',
          label_text_color=None)
graph.render("./img/关系图.html")
Esempio n. 33
0
from pyecharts import Graph
import json
with open("..jsonweibo.json", "r", encoding="utf-8") as f:
    j = json.load(f)
    nodes, links, categories, cont, mid, userl =i j 
    graph =Graph("微博转发关系图", width=1200, height=600)
    graph.add("", nodes, links, categories, label_pos="right", repulsion=50, is_legend_show=False, line_curve=0.2, label_text_color=None)
    graph.show_config()
    graph.render()
Esempio n. 34
0
def test_graph():

    # graph_0
    nodes = [{"name": "结点1", "symbolSize": 10},
             {"name": "结点2", "symbolSize": 20},
             {"name": "结点3", "symbolSize": 30},
             {"name": "结点4", "symbolSize": 40},
             {"name": "结点5", "symbolSize": 50},
             {"name": "结点6", "symbolSize": 40},
             {"name": "结点7", "symbolSize": 30},
             {"name": "结点8", "symbolSize": 20}]
    links = []
    for i in nodes:
        for j in nodes:
            links.append({"source": i.get('name'), "target": j.get('name')})
    graph = Graph("关系图-力引导布局示例")
    graph.add("", nodes, links, repulsion=8000)
    graph.show_config()
    graph.render()

    # graph_1
    graph = Graph("关系图-环形布局示例")
    graph.add("", nodes, links, is_label_show=True, repulsion=8000, layout='circular', label_text_color=None)
    graph.show_config()
    graph.render()

    # graph_2
    import json
    if PY2:
        import codecs
        with codecs.open(os.path.join("..", "json", "weibo.json"), "rb") as f:
            j = json.load(f)
    else:
        with open(os.path.join("..", "json", "weibo.json"), "r", encoding="utf-8") as f:
            j = json.load(f)
    nodes, links, categories, cont, mid, userl = j
    graph = Graph("微博转发关系图", width=1200, height=600)
    graph.add("", nodes, links, categories, label_pos="right", repulsion=50, is_legend_show=False, line_curve=0.2,
              label_text_color=None)
    graph.show_config()
    graph.render()