跳過到頁腳內容
PYTHON 幫助

igraph python(開發人員如何工作)

圖形和複雜網路研究是計算機科學和數學的基本概念,用於建模複雜的連接和交互。 圖形的節點(有時也稱為頂點)和邊(有時稱為連結)實質上只是實體及其關係的可視化表示和解釋,通過連接節點的邊顯示出來。

更普遍地說,用於交通系統、社交網路和通信網路的所有圖形都被認為是網路。 通過查看圖形和網路,我們可以理解和解決與連接性、流動性和網路結構相關的問題。 這樣的工作提供了對社會動態和組織結構的多樣化領域的洞察,從高效路由和優化的算法到社會動態和組織結構。 這些概念在網路理論、運籌學和數據科學中非常中心。

在這篇文章中,我們使用 igraph 展示如何生成網路圖並使用靈活且可靠的 IronPDF 庫將其打印成 PDF 文件。

什麼是 igraph?

Igraph 是一個強大的 Python 包,用於生成、操作和分析複雜的圖形和網路。 它提供了一個巨大的工具包來處理圖形,從生成到操作及其可視化。 Python igraph 通過許多算法計算各種中心性指標、最短路徑、社群結構等,促進網路分析的實施。

因此,該庫以自適應佈局和屬性提供了良好的可視化,適用於有向和無向圖。Igraph 非常靈活和快速,經常用於分析困難的關係數據的應用中,如數據科學、計算生物學和社交網路研究。

igraph python(開發者運作方式):圖 1 - Igraph 頁面

設置和使用 igraph Python 包

要開始使用 Python 中的基本圖論操作和配置,請按照以下步驟自行創建、配置和使用 igraph。

安裝 igraph 包

您必須先安裝 igraph 包。可以使用以下 pip 命令進行安裝:

pip install igraph
pip install igraph
SHELL

使用 Igraph 創建圖形

這裡有一個簡單的例子,向您展示如何使用 igraph 來構建和設置圖形:

from igraph import Graph, plot

# Create an empty graph
g = Graph()

# Add vertices (nodes)
g.add_vertices(5)  # Adding 5 vertices

# Add edges (connections between vertices)
g.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)])  # Adding edges

# Add vertex ids and edge attributes
g.vs["name"] = ["A", "B", "C", "D", "E"]  # Vertex labels
g.es["weight"] = [1, 2, 3, 4, 5, 6]  # Edge weights

# Print basic graph structural properties
print("Number of vertices:", g.vcount())
print("Number of edges:", g.ecount())
print("Graph summary:", g.summary())
from igraph import Graph, plot

# Create an empty graph
g = Graph()

# Add vertices (nodes)
g.add_vertices(5)  # Adding 5 vertices

# Add edges (connections between vertices)
g.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)])  # Adding edges

# Add vertex ids and edge attributes
g.vs["name"] = ["A", "B", "C", "D", "E"]  # Vertex labels
g.es["weight"] = [1, 2, 3, 4, 5, 6]  # Edge weights

# Print basic graph structural properties
print("Number of vertices:", g.vcount())
print("Number of edges:", g.ecount())
print("Graph summary:", g.summary())
PYTHON

控制台輸出

igraph python(開發者運作方式):圖 2 - 代碼示例的控制台輸出

配置圖形佈局和可視化

我們可以使用 igraph 的一些內置功能來繪製圖形。 使用以下內容更改外觀和佈局:

# Define a layout for the graph
layout = g.layout("circle")  # Layout in a circular arrangement

# Plot the graph with labels and custom options
plot(
    g,
    layout=layout,
    vertex_label=g.vs["name"],  # Label vertices
    vertex_color="lightblue",   # Vertex color
    edge_width=g.es["weight"],  # Edge width based on weight
    vertex_size=30,             # Vertex size
    edge_color="grey",          # Edge color
    bbox=(300, 300),            # Size of the plot
    margin=20                   # Margin around the plot
)

# Save the plotted graph to a file
plot(g, layout=layout, bbox=(300, 300), margin=20).save('exampleGraph.png') 
# Define a layout for the graph
layout = g.layout("circle")  # Layout in a circular arrangement

# Plot the graph with labels and custom options
plot(
    g,
    layout=layout,
    vertex_label=g.vs["name"],  # Label vertices
    vertex_color="lightblue",   # Vertex color
    edge_width=g.es["weight"],  # Edge width based on weight
    vertex_size=30,             # Vertex size
    edge_color="grey",          # Edge color
    bbox=(300, 300),            # Size of the plot
    margin=20                   # Margin around the plot
)

# Save the plotted graph to a file
plot(g, layout=layout, bbox=(300, 300), margin=20).save('exampleGraph.png') 
PYTHON

輸出圖形

下面是使用 Matplotlib 庫和 Cairo 庫的 Python 綁定生成的簡單圖形圖像。

igraph python(開發者運作方式):圖 3 - 輸出圖形

高級圖形操作

執行各種圖形操作和分析,如計算中心性、尋找社區或識別最短路徑:

# Calculate degree centrality for each vertex
degrees = g.degree()
print("Degrees of vertices:", degrees)

# Compute shortest path between two vertices that don't have a predefined distance
shortest_path = g.shortest_paths_dijkstra(source=0, target=3)
print("Shortest path from vertex 0 to 3:", shortest_path)

# Detect communities using the Louvain method
communities = g.community_multilevel()
print("Detected communities:", communities)
# Calculate degree centrality for each vertex
degrees = g.degree()
print("Degrees of vertices:", degrees)

# Compute shortest path between two vertices that don't have a predefined distance
shortest_path = g.shortest_paths_dijkstra(source=0, target=3)
print("Shortest path from vertex 0 to 3:", shortest_path)

# Detect communities using the Louvain method
communities = g.community_multilevel()
print("Detected communities:", communities)
PYTHON

控制台輸出s

igraph python(開發者運作方式):圖 4 - 之前計算的控制台輸出

介紹 IronPDF

igraph python(開發者運作方式):圖 5 - IronPDF 網頁

我們甚至可以使用 IronPDF Python 模塊編程生成和編輯 PDF。 使用此庫,您將擁有巨大的能力來從 HTML 創建 PDF 文檔、合併兩個或多個 PDF 文檔,甚至利用現有的 PDFs 並修改它們以包含文本、照片和註釋。 IronPDF 使您能夠從任何 HTML 網站或符合報告、發票和其他具有預設樣式的文檔生成的 Web 內容生成專業質量的 PDF。

其一些高級功能包括編輯頁面佈局、文檔加密和從 PDF 中提取文字。 如果開發者能夠更好地處理 PDF,他們將更好地提高產品的整體實用性。

安裝 IronPDF 庫

您可以使用以下命令來安裝允許 Python 接口激活 IronPDF 能力的包以用於您的項目:

 pip install ironpdf

將 igraph 與 IronPDF 集成

以下是在 Python 中合併 igraph 和 IronPDF 的步驟:首先,您將使用 igraph 創建一個圖形並顯示它。 然後,將結果可視化變為 PDF。

from igraph import Graph, plot
import matplotlib.pyplot as plt
from ironpdf import ImageToPdfConverter, License
import warnings

# Suppress warnings for cleaner output
warnings.filterwarnings('ignore')

# Ensure that you have replaced the string with your own license key
License.LicenseKey = "YOUR LICENSE KEY GOES HERE"

# Create an empty graph
g = Graph()

# Add adjacent vertices (nodes)
g.add_vertices(5)  # Adding 5 vertices

# Add edges (connections between vertices)
g.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)])  # Adding edges

# Add vertex and edge attributes
g.vs["name"] = ["A", "B", "C", "D", "E"]  # Vertex labels
g.es["weight"] = [1, 2, 3, 4, 5, 6]  # Edge weights

# Define a layout for the graph
layout = g.layout("circle")  # Layout in a circular arrangement

# Create a plot using matplotlib
fig, ax = plt.subplots()

# Plot the graph with specified layout and styles
plot(
    g,
    target=ax,
    layout=layout,
    vertex_label=g.vs["name"],  # Label vertices
    vertex_color="lightblue",   # Vertex color
    edge_width=g.es["weight"],  # Edge width based on weight
    vertex_size=30,             # Vertex size
    edge_color="grey",          # Edge color
    bbox=(300, 300),            # Size of the plot
    margin=20                   # Margin around the plot
)

# Save the plot as a PNG image
plt.savefig('result.png')

# Convert the image to a PDF file
ImageToPdfConverter.ImageToPdf('result.png').SaveAs("result.pdf")
from igraph import Graph, plot
import matplotlib.pyplot as plt
from ironpdf import ImageToPdfConverter, License
import warnings

# Suppress warnings for cleaner output
warnings.filterwarnings('ignore')

# Ensure that you have replaced the string with your own license key
License.LicenseKey = "YOUR LICENSE KEY GOES HERE"

# Create an empty graph
g = Graph()

# Add adjacent vertices (nodes)
g.add_vertices(5)  # Adding 5 vertices

# Add edges (connections between vertices)
g.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)])  # Adding edges

# Add vertex and edge attributes
g.vs["name"] = ["A", "B", "C", "D", "E"]  # Vertex labels
g.es["weight"] = [1, 2, 3, 4, 5, 6]  # Edge weights

# Define a layout for the graph
layout = g.layout("circle")  # Layout in a circular arrangement

# Create a plot using matplotlib
fig, ax = plt.subplots()

# Plot the graph with specified layout and styles
plot(
    g,
    target=ax,
    layout=layout,
    vertex_label=g.vs["name"],  # Label vertices
    vertex_color="lightblue",   # Vertex color
    edge_width=g.es["weight"],  # Edge width based on weight
    vertex_size=30,             # Vertex size
    edge_color="grey",          # Edge color
    bbox=(300, 300),            # Size of the plot
    margin=20                   # Margin around the plot
)

# Save the plot as a PNG image
plt.savefig('result.png')

# Convert the image to a PDF file
ImageToPdfConverter.ImageToPdf('result.png').SaveAs("result.pdf")
PYTHON

此腳本將通過 igraph 生成圖形,使用 matplotlib 進行可視化,然後使用 IronPDF 將圖表轉換成 PDF。 該代碼將導入所有必要的庫並設置 IronPDF 的許可密鑰。 創建一個具有五個頂點和六條邊的空圖,並添加權重和標籤以清晰顯示。

圖形以圓形佈置,並且繪圖涉及到許多可視化屬性,如頂點顏色和大小、邊的線寬。 之後,結果作為圖片文件result.png被保存下來。 最後,它使用 IronPDF 的ImageToPdfConverter 轉化為 PDF result.pdf。 圖形創建、可視化和PDF生成被合併到一個工作流中。

輸出的 PDF

igraph python(開發者運作方式):圖 6 - 輸出的 PDF

授權

需要授權密鑰允許代碼在沒有水印的情況下工作。 您可以在此鏈接中註冊一個免費試用許可證。 請注意,註冊過程不需要提供身份證明。 您只需要輸入您的電子郵件地址即可註冊免費試用版本。

igraph python(開發者運作方式):圖 7 - IronPDF 許可計畫

結論

通過IronPDF和 igraph 的力量,您可以開發出可視化和展示複雜圖形數據的解決方案。 通過 igraph,您可以輕鬆地創建和分析複雜的網絡,同時使用 IronPDF 將數據可視化無縫轉換成專業級的 PDF 文件。 這些結合的力量將幫助您開發綜合報告,包括圖形分析和可視化表達。

這種整合支持各種應用的開發,這些應用需要全面的網絡文檔,包括學術研究、商業分析和數據驅動的報告。 此外,它結合了高質量的文檔輸出和對圖形非常強大的操控能力。最重要的是,Iron Software提供多種庫,簡化了 Windows、Android、MAC、Linux 等操作系統和平台上的應用開發。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。