You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python结合Matplotlib绘制桁架结构示意图?

桁架结构示意图绘制解决方案

原代码问题分析

原代码出现索引越界及功能失效的原因:

  • 未利用elements列表定义的杆件连接关系,桁架的杆件逻辑完全依赖该列表
  • 对nodes结构理解错误:nodes中每个元素是[节点编号, x坐标, y坐标],多层索引nodes[i][j][1][1]完全不符合结构,直接导致索引越界
  • 未初始化变量mmc就进行操作
  • 函数仅接收nodes参数,缺失关键的elements参数

正确实现代码

import matplotlib.pyplot as plt

def draw_truss(nodes, elements):
    # 将节点列表转换为字典,方便通过节点编号快速查询坐标
    node_dict = {int(node[0]): (node[1], node[2]) for node in nodes}
    
    plt.figure(figsize=(8, 6))
    
    # 绘制所有杆件
    for elem in elements:
        _, start_node, end_node = elem
        # 获取起点和终点坐标
        x1, y1 = node_dict[start_node]
        x2, y2 = node_dict[end_node]
        # 绘制杆件线段
        plt.plot([x1, x2], [y1, y2], '-', color='gray', linewidth=2)
    
    # 绘制所有节点
    xs = [coord[0] for coord in node_dict.values()]
    ys = [coord[1] for coord in node_dict.values()]
    plt.scatter(xs, ys, color='red', s=60, zorder=5)
    
    # 添加节点编号标注
    for node_num, (x, y) in node_dict.items():
        plt.text(x + 0.05, y + 0.05, str(node_num), fontsize=12)
    
    # 设置坐标轴和标题
    plt.axis('equal')
    plt.title('桁架结构示意图')
    plt.xlabel('X坐标')
    plt.ylabel('Y坐标')
    plt.grid(True, linestyle='--', alpha=0.7)
    plt.show()

# 测试示例数据
elements = [[1, 1, 2], [2, 2, 3], [3, 3, 4], [4, 4, 5], [5, 5, 1], [6, 1, 4], [7, 2, 4], [8, 4, 6], [9, 6, 5]]
nodes= [[1.0, 0.0, 1.2], [2.0, -1.5, 1.2], [3.0, -1.5, 0.0], [4.0, 0.0, 0.0], [5.0, 1.5, 1.2], [6.0, 1.5, 0.0]]

draw_truss(nodes, elements)

代码说明

  • 节点字典构建:将节点列表转为以节点编号为键的字典,避免遍历查找坐标,提升效率
  • 杆件绘制:遍历elements中的每个杆件,通过节点编号获取两端坐标,绘制线段
  • 节点绘制:提取所有节点坐标,用红色圆点标记,设置zorder=5确保节点显示在杆件上方
  • 辅助优化:添加节点编号标注、等比例坐标轴、网格线,提升图形可读性

内容的提问来源于stack exchange,提问作者user20276952

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:01:37