Comment créer une représentation graphique (n'inporte quel graphique ) en python ?

Asked  Mar 03, 05:23 pm 15 Views Add Your Answer
Asked  Mar 03, 05:23 pm
0 Dislikes
0 Comments

1 Answers

Added  Mar 04, 01:21 pm

In Python, you can use various libraries to create a graph representation of any graph, such as NetworkX, Matplotlib, and Plotly. Here's an example using NetworkX:

First, you need to install the library using pip:

pip install networkx

Then, you can create a graph using NetworkX by defining the nodes and edges:

import networkx as nx
import matplotlib.pyplot as plt

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

# Add nodes to the graph
G.add_nodes_from([1, 2, 3, 4, 5])

# Add edges to the graph
G.add_edge(1, 2)
G.add_edge(1, 3)
G.add_edge(2, 3)
G.add_edge(2, 4)
G.add_edge(3, 4)
G.add_edge(4, 5)

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

This will create a graph with 5 nodes and 6 edges, and display it using Matplotlib.

You can customize the graph by specifying different properties, such as node color, edge weight, and layout. Here's an example:

import networkx as nx
import matplotlib.pyplot as plt

# Create a graph
G = nx.Graph()

# Add nodes to the graph
G.add_nodes_from([1, 2, 3, 4, 5])

# Add edges to the graph
G.add_edge(1, 2, weight=2)
G.add_edge(1, 3, weight=1)
G.add_edge(2, 3, weight=3)
G.add_edge(2, 4, weight=2)
G.add_edge(3, 4, weight=1)
G.add_edge(4, 5, weight=4)

# Set node color
node_color = ['blue', 'red', 'green', 'yellow', 'purple']

# Set edge weight
edge_width = [d['weight'] for (u, v, d) in G.edges(data=True)]

# Set layout
pos = nx.spring_layout(G)

# Draw the graph with custom properties
nx.draw(G, pos=pos, node_color=node_color, with_labels=True, width=edge_width)
plt.show()

This will create a graph with custom properties, such as node color, edge weight, and layout, and display it using Matplotlib.

1 Likes 0 Dislikes
0 Comments
×
SignUp with Email
X