Python基于pyecharts實(shí)現(xiàn)關(guān)聯(lián)圖繪制
生活中有很多需要用到關(guān)聯(lián)圖的地方,至少我認(rèn)為的是這樣的圖:https://www.echartsjs.com/examples/zh/editor.html?c=graph-npm

我是在使用Word2Vec計(jì)算關(guān)聯(lián)詞的余弦距離之后,想要更好的展示出來的時(shí)候,遇到的這種情況,就做了下拓展。
畫圖的步驟主要分為:
1. 將距離數(shù)據(jù)(或者相關(guān)數(shù)據(jù))讀入;
2. 按照一定的格式和參數(shù)將數(shù)據(jù)保存為json字符串;
3. 根據(jù)json串,繪制關(guān)聯(lián)圖。
具體而言,主要是:
<1>. 首先有一批數(shù)據(jù),如圖所示:

<2>. 導(dǎo)入所需要的包
import json
import pandas as pd
import random
import copy
<3>. 產(chǎn)生顏色隨機(jī)值的函數(shù)
# 隨機(jī)顏色
def randomcolor_func():
color_char = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
color_code = ""
for i in range(6):
color_code += color_char[random.randint(0,14)] # randint包括前后節(jié)點(diǎn)0和14
return "#"+color_code
<4>. 生成隨機(jī)坐標(biāo)
# 隨機(jī)坐標(biāo)
#生成隨機(jī)數(shù),浮點(diǎn)類型
def generate_position(n):
# n = 10
for i in range(n):
x = round(random.uniform(-2000, 2000), 5) #一定范圍內(nèi)的隨機(jī)數(shù),范圍可變
y = round(random.uniform(-2000, 2000), 5) #控制隨機(jī)數(shù)的精度round(數(shù)值,精度)
return x, y
<5>. 生成json格式的節(jié)點(diǎn)數(shù)據(jù)
def create_json(data, weights):
# 自定義節(jié)點(diǎn)
address_dict = {"nodes":[], "edges":[]}
node_dict = {
"color": "",
"label": "",
"attributes": {},
"y": None,
"x": None,
"id": "",
"size": None
}
edge_dict = {
"sourceID": "",
"attributes": {},
"targetID": "",
"size": None
}
# 給節(jié)點(diǎn)賦值
for ii in range(len(data)):
for jj in range(len(data.iloc[ii])):
# node,"attributes"屬性可自行設(shè)置
node_dict[r"color"] = randomcolor_func()
node_dict[r"label"] = data.iloc[ii, jj]
x, y = generate_position(1)
node_dict[r"y"] = y
node_dict[r"x"] = x
node_dict[r"id"] = data.iloc[ii, jj]
node_dict[r"size"] = int(weights.loc[data.iloc[ii, jj]])
tmp_node = copy.deepcopy(node_dict)
address_dict[r"nodes"].append(tmp_node)
for ii in range(len(data)):
for jj in range(1, len(data.iloc[ii])):
# edge
edge_dict[r"sourceID"] = data.iloc[ii, 0]
edge_dict[r"targetID"] = data.iloc[ii, jj]
edge_dict[r"size"] = 2
tmp_edge = copy.deepcopy(edge_dict)
address_dict["edges"].append(tmp_edge)
return address_dict
<6>. 主函數(shù)生成json數(shù)據(jù)
if __name__ == '__main__':
# read data
data = pd.read_excel(r'test_josn_data.xlsx', 0)
weights = pd.DataFrame({"詞頻":[100, 40, 30, 20, 90, 50, 35, 14, 85, 38, 29, 10]},
index = ['球類','籃球','足球','羽毛球','美食','肯德基','火鍋','烤魚','飲料','可樂','紅茶','奶茶']) #建立索引權(quán)值列表
address_dict = create_json(data, weights)
with open("write_json.json", "w", encoding='utf-8') as f:
# json.dump(dict_, f) # 寫為一行
json.dump(address_dict, f, indent=2, ensure_ascii=False) # 寫為多行
最后形成的json數(shù)據(jù)如下:

<7>. 繪制關(guān)聯(lián)圖,里面的文件讀取和保存地址自行修改,write_json.json 就是上面保存的json文件
import pyecharts.options as opts
from pyecharts.charts import Graph
import json
with open(r"D:\Python_workspace\spyder_space\test_各種功能\write_json.json", encoding='utf-8') as f: #設(shè)置以u(píng)tf-8解碼模式讀取文件,encoding參數(shù)必須設(shè)置,否則默認(rèn)以gbk模式讀取文件,當(dāng)文件中包含中文時(shí),會(huì)報(bào)錯(cuò)
data = json.load(f)
#print(data)
nodes = [
{
"x": node["x"],
"y": node["y"],
"id": node["id"],
"name": node["label"],
"symbolSize": node["size"],
"itemStyle": {"normal": {"color": node["color"]}},
}
for node in data["nodes"]
]
edges = [{"source": edge["sourceID"], "target": edge["targetID"]} for edge in data["edges"]]
(
Graph(init_opts=opts.InitOpts(width="1600px", height="800px"))
.add(
series_name="",
nodes=nodes,
links=edges,
layout="none",
is_roam=True,
is_focusnode=True,
label_opts=opts.LabelOpts(is_show=True),
linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3, opacity=0.7),
)
.set_global_opts(title_opts=opts.TitleOpts(title="熱詞對(duì)應(yīng)的關(guān)聯(lián)詞"))
.render("關(guān)聯(lián)詞圖.html")
)
最后,就生成了最開始的那張圖。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解如何使用Pandas創(chuàng)建有效且可復(fù)制的代碼
Pandas作為一種多功能和強(qiáng)大的工具而屹立不倒,其直觀的數(shù)據(jù)結(jié)構(gòu)和廣泛的功能使其成為無數(shù)數(shù)據(jù)專業(yè)人士和愛好者的首選,本文將使用Pandas創(chuàng)建有效且可復(fù)制的代碼,感興趣的可以了解下2024-11-11
python3中@dataclass的實(shí)現(xiàn)示例
@dataclass?是 Python 3.7 引入的一個(gè)裝飾器,用于方便地定義符合數(shù)據(jù)類協(xié)議的類,本文主要介紹了python3中@dataclass的實(shí)現(xiàn)示例,感興趣的可以了解一下2024-02-02
pandas實(shí)現(xiàn)將dataframe滿足某一條件的值選出
今天小編就為大家分享一篇pandas實(shí)現(xiàn)將dataframe滿足某一條件的值選出,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python連接MySQL并使用fetchall()方法過濾特殊字符
這篇文章主要介紹了Python連接MySQL的方法并講解了如何使用fetchall()方法過濾特殊字符,示例環(huán)境為Ubuntu操作系統(tǒng),需要的朋友可以參考下2016-03-03
python神經(jīng)網(wǎng)絡(luò)Xception模型復(fù)現(xiàn)詳解
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)Xception模型復(fù)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python3實(shí)現(xiàn)公眾號(hào)每日定時(shí)發(fā)送日?qǐng)?bào)和圖片
這篇文章主要為大家詳細(xì)介紹了python3實(shí)現(xiàn)公眾號(hào)每日定時(shí)發(fā)送日?qǐng)?bào)和圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
python?label與one-hot之間的互相轉(zhuǎn)換方式
這篇文章主要介紹了python?label與one-hot之間的互相轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02

