[파이썬] matplotlib 네트워크 그래프 그리기

In this blog post, we will explore how to use the matplotlib library in Python to create network graphs. Network graphs, also known as a “graph” or “network,” represent connections between nodes using lines or edges.

Installing matplotlib

Before we start, make sure you have matplotlib installed in your Python environment. You can install it using pip with the following command:

pip install matplotlib

Creating a Simple Network Graph

Let’s start by creating a simple network graph using matplotlib. First, import the necessary libraries:

import matplotlib.pyplot as plt
import networkx as nx

Next, create a graph object and add nodes and edges to it:

# Create an empty graph
G = nx.Graph()

# Add nodes
G.add_nodes_from([1, 2, 3, 4])

# Add edges
G.add_edges_from([(1, 2), (1, 3), (2, 3), (3, 4)])

Now, we can draw the network graph using matplotlib:

# Draw the graph
nx.draw(G, with_labels=True)

# Display the graph
plt.show()

Customizing the Network Graph

You can customize the appearance of the network graph by changing its colors, layout, labels, and more. Here are a few examples:

Changing Node Colors

You can change the color of nodes using the node_color parameter:

nx.draw(G, with_labels=True, node_color='red')

Changing Edge Colors

You can change the color of edges using the edge_color parameter:

nx.draw(G, with_labels=True, edge_color='blue')

Changing the Graph Layout

You can change the layout of the graph using the pos parameter. There are several options available, such as spring_layout, spectral_layout, and circular_layout:

nx.draw(G, with_labels=True, pos=nx.spring_layout(G))

Adding Labels to Nodes

You can add labels to nodes using the labels parameter:

labels = {1: 'Node 1', 2: 'Node 2', 3: 'Node 3', 4: 'Node 4'}
nx.draw(G, with_labels=True, labels=labels)

Conclusion

In this blog post, we learned how to create network graphs using matplotlib in Python. We explored the basics of creating a simple network graph and customizing its appearance. With matplotlib, you can create visually appealing network graphs to represent connections between nodes in your data.