Stay organized with collections
Save and categorize content based on your preferences.
Write Python code to visualize a weighted directed graph with example data
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.
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
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()
Explanation:
Import necessary libraries:
matplotlib.pyplot for plotting the graph.
networkx for creating and manipulating the graph.
Define example data:
nodes: A list of node names.
edges: A list of tuples representing directed edges, where each tuple is (source node, target node).
Create a directed graph object:
graph = nx.DiGraph(): Creates an empty directed graph object.
Add nodes and edges:
graph.add_nodes_from(nodes): Adds all nodes from the nodes list to the graph.
graph.add_edges_from(edges): Adds all edges from the edges list to the graph.
Draw the graph:
nx.draw(graph, ...): Draws the graph using matplotlib.
with_labels=True: Displays node labels.
node_color='lightblue': Sets the node color to light blue.
node_size=500: Sets the node size.
font_size=10: Sets the font size for labels.
arrowsize=20: Sets the arrow size for edges.
Display the graph:
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.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-12-20 UTC."],[],[]]