Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

图上有15个点,每个点都有8条红线去连接其它8个点以及有6条蓝线连接剩余的6个点。请生成python代码来画出这张图。

  1. User

    图上有15个点,每个点都有8条红线去连接其它8个点以及有6条蓝线连接剩余的6个点。请生成python代码来画出这张图。

  2. Assistant

    要绘制这样一张图,你可以使用 networkx 来创建和管理图,然后使用 matplotlib 来进行可视化。以下是一个实现这个需求的代码示例:

    import networkx as nx
    import matplotlib.pyplot as plt
    import random
    
    def draw_custom_graph():
        # Create an empty graph
        G = nx.Graph()
    
        # Add 15 nodes
        nodes = range(15)
        G.add_nodes_from(nodes)
    
        # For each node, add 8 red edges and 6 blue edges
        for node in nodes:
            # Get the list of other nodes
            other_nodes = list(set(nodes) - {node})
            random.shuffle(other_nodes)
            # Select 8 nodes for red edges and the remaining 6 for blue edges
            red_neighbors = other_nodes[:8]
            blue_neighbors = other_nodes[8:14]
    
            # Add red edges
            for neighbor in red_neighbors:
                G.add_edge(node, neighbor, color='red')
    
            # Add blue edges
            for neighbor in blue_neighbors:
                G.add_edge(node, neighbor, color='blue')
    
        # Get the color map for edges
        edges = G.edges(data=True)
        edge_colors = [e[2]['color'] for e in edges]
    
        # Draw the graph
        pos = nx.spring_layout(G, seed=42)  # can adjust layout or use a fixed seed for reproducibility
        nx.draw(G, pos, edge_color=edge_colors, with_labels=True, node_color='lightgray', node_size=500)
    
        # Show plot
        plt.show()
    
    # Call to draw the graph
    draw_custom_graph()
    

    解释:

    • 我们用 networkx 创建图对象 G。
    • 图中有 15 个节点,编号为 0 到 14。
    • 然后,我们给每个节点连接到 8 个其它节点的红边和剩下的 6 个节点的蓝边。
    • 使用 networkx 和 matplotlib 来绘制图,这些库提供了简单的可视化方法。
    • 我们通过 spring_layout 来安排节点位置,也可以根据需求切换到其他布局方式。
    • 绘图时用 edge_color 参数来分别显示红色和蓝色边。

    请确保在运行代码之前安装 networkx 和 matplotlib,可通过命令 pip install networkx matplotlib 安装。