Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Écrire du code Python pour visualiser un graphique dirigé pondéré avec des données d'exemple
Vous pouvez interroger un modèle directement et tester les résultats renvoyés lors de l'utilisation de différentes valeurs de paramètre en utilisant la console Cloud ou en appelant directement l'API Vertex AI.
Écrire du code Python pour dessiner un graphique orienté à l'aide de matplotlib et de networkx Montrez comment utiliser le code avec des exemples de données. Incluez toutes les instructions d'importation nécessaires.
Réponse
importmatplotlib.pyplotaspltimportnetworkxasnx# Example data: a directed graph with nodes and edgesnodes=['A','B','C','D','E']edges=[('A','B'),('A','C'),('B','D'),('C','E'),('D','E')]# Create a directed graph objectgraph=nx.DiGraph()# Add nodes to the graphgraph.add_nodes_from(nodes)# Add edges to the graphgraph.add_edges_from(edges)# Draw the graph using matplotlibnx.draw(graph,with_labels=True,node_color='lightblue',node_size=500,font_size=10,arrowsize=20)# Display the graphplt.show()
Explication :
Importer les bibliothèques nécessaires :
matplotlib.pyplot pour tracer le graphique
networkx pour créer et manipuler le graphique
Définir des exemples de données :
nodes : liste de noms de nœuds.
edges : liste de tuples représentant les arêtes dirigées, où se trouve chaque tuple (nœud source, nœud cible)
Créer un objet graphique orienté :
graph = nx.DiGraph() : crée un objet de graphique orienté vide.
Ajouter des nœuds et des arêtes :
graph.add_nodes_from(nodes) : ajoute tous les nœuds de la liste nodes au graphique.
graph.add_edges_from(edges) : ajoute toutes les arêtes de la liste edges au graphique.
Dessiner le graphique :
nx.draw(graph, ...) : dessine le graphe à l'aide de matplotlib.
with_labels=True : affiche les libellés de nœud.
node_color='lightblue' : définit la couleur du nœud sur bleu clair.
node_size=500 : définit la taille du nœud.
font_size=10 : définit la taille de la police pour les libellés.
arrowsize=20 : définit la taille des flèches pour les arêtes.
Afficher le graphique :
plt.show() : affiche le graphique représenté.
Résultat :
Ce code génère une visualisation de graphique orienté avec les nœuds et les arêtes spécifiés. Les nœuds seront étiquetés, de couleur bleu clair et reliés par des flèches représentant la direction des arêtes.
Modèle :
gemini-1.5-flash-001
Température :
1
Nombre maximal de jetons de sortie :
8 192
TopK :
40
TopP :
0,95
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[],[],null,["Write Python code to visualize a weighted directed graph with example data\n\n|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| You can query a model directly and test the results returned when using different parameter values with the Cloud console, or by calling the Vertex AI API directly. - For an example of using the Vertex AI API, see [Quickstart using the Vertex AI API](/vertex-ai/generative-ai/docs/start/quickstarts/api-quickstart). - To view this sample in the Cloud console: [Go to Google Cloud console](https://console.cloud.google.com/vertex-ai/generative/language/prompt-examples/Python%20visualization) \u003cbr /\u003e ||\n| Prompt Freeform Write Python code to draw a directed graph using matplotlib and networkx. Show how to use the code with some example data. Include all necessary import statements. Response import matplotlib.pyplot as plt import networkx as nx # Example data: a directed graph with nodes and edges nodes = ['A', 'B', 'C', 'D', 'E'] edges = [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'E'), ('D', 'E')] # Create a directed graph object graph = nx.DiGraph() # Add nodes to the graph graph.add_nodes_from(nodes) # Add edges to the graph graph.add_edges_from(edges) # Draw the graph using matplotlib nx.draw(graph, with_labels=True, node_color='lightblue', node_size=500, font_size=10, arrowsize=20) # Display the graph plt.show() **Explanation:** 1. **Import necessary libraries:** 2. `matplotlib.pyplot` for plotting the graph. 3. `networkx` for creating and manipulating the graph. 4. **Define example data:** 5. `nodes`: A list of node names. 6. `edges`: A list of tuples representing directed edges, where each tuple is (source node, target node). 7. **Create a directed graph object:** 8. `graph = nx.DiGraph()`: Creates an empty directed graph object. 9. **Add nodes and edges:** 10. `graph.add_nodes_from(nodes)`: Adds all nodes from the `nodes` list to the graph. 11. `graph.add_edges_from(edges)`: Adds all edges from the `edges` list to the graph. 12. **Draw the graph:** 13. `nx.draw(graph, ...)`: Draws the graph using matplotlib. 14. `with_labels=True`: Displays node labels. 15. `node_color='lightblue'`: Sets the node color to light blue. 16. `node_size=500`: Sets the node size. 17. `font_size=10`: Sets the font size for labels. 18. `arrowsize=20`: Sets the arrow size for edges. 19. **Display the graph:** 20. `plt.show()`: Shows the plotted graph. **Output:** This code will generate a directed graph visualization with the specified nodes and edges. The nodes will be labeled, colored light blue, and connected by arrows representing the direction of the edges. | |------------------------|----------------------| | **Model:** | gemini-1.5-flash-001 | | **Temperature:** | 1 | | **Max output tokens:** | 8192 | | **TopK:** | 40 | | **TopP:** | 0.95 | |"]]