python画图代码
时间: 2023-09-25 22:14:45 浏览: 98
以下是Python中使用NetworkX库绘制图形的代码示例:
```python
import networkx as nx
import matplotlib.pyplot as plt
# 创建一个空的有向图
g = nx.DiGraph()
# 添加节点
g.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
# 添加边
g.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (1, 9), (6, 7), (6, 8), (1, 6), (6, 9), (9, 10), (9, 11)])
# 设置节点位置
fixed_pos = {1: (0, 0), 2: (1, 1), 3: (-1, 1), 4: (1, -1), 5: (-1, -1), 6: (2, 0), 7: (3, 1), 8: (3, -1), 9: (4, 0), 10: (5, 1), 11: (5, -1)}
# 绘制图形
plt.figure(figsize=(8, 6))
nx.draw_networkx_nodes(g, pos=fixed_pos, node_size=600)
nx.draw_networkx_edges(g, pos=fixed_pos, edgelist=[(1, 2), (1, 3), (1, 4), (1, 5), (1, 9)], edge_color='g', width=[4.0, 4.0, 4.0, 4.0, 4.0], label=[1, 2, 3, 4, 5], node_size=600)
nx.draw_networkx_edges(g, pos=fixed_pos, edgelist=[(6, 7), (6, 8), (1, 6)], width=[4.0, 4.0, 4.0], edge_color='r', node_size=600)
nx.draw_networkx_edges(g, pos=fixed_pos, edgelist=[(6, 9), (9, 10), (9, 11)], width=[4.0, 4.0, 4.0], edge_color='b', node_size=600)
plt.axis('off')
plt.legend()
plt.show()
```
这段代码使用NetworkX库创建了一个有向图,然后通过添加节点和边来构建图形。最后使用`nx.draw_networkx_nodes`和`nx.draw_networkx_edges`方法绘制了图形,并设置了节点位置、边的样式和宽度。最后使用matplotlib库展示了图形。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [python画图代码大全-Python科学画图代码分享](https://blog.csdn.net/q6q6q/article/details/109341451)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文