networkx 例子

以下代码在Jupyter Notebook中运行:
‘’’
draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color=‘k’,style=‘solid’,alpha=1.0,
edge_cmap=None, edge_vmin=None,edge_vmax=None, ax=None, arrows=True,label=None, **kwds):

G:图表 一个networkx图
pos:dictionary 将节点作为键和位置作为值的字典。位置应该是长度为2的序列。
edgelist:边缘元组的集合,只绘制指定的边(默认= G.edges())
width:float或float数组,边线宽度(默认值= 1.0)
edge_color:颜色字符串或浮点数组,边缘颜色。可以是单颜色格式字符串(default =‘r’),或者具有与edgelist相同长度的颜色序列。
如果指定了数值,它们将被映射到颜色使用edge_cmap和edge_vmin,edge_vmax参数。
style:string 边线样式(默认=‘solid’)(实线|虚线|点线,dashdot)
alpha:float 边缘透明度(默认值= 1.0)
edge_ cmap:Matplotlib色彩映射,用于映射边缘强度的色彩映射(默认值=无)
edge_vmin,edge_vmax:float 边缘色图缩放的最小值和最大值(默认值=无)
ax:Matplotlib Axes对象,可选,在指定的Matplotlib轴中绘制图形。
arrows:bool,optional(default = True)对于有向图,如果为真,则绘制箭头。
label:图例的标签
‘’’
‘’’
draw_networkx_nodes(G, pos, nodelist=None,node_size=300,node_color=‘r’,node_shape=‘o’,alpha=1.0,
cmap=None,vmin=None,vmax=None,ax=None,linewidths=None,label=None,**kwds):

G:图表,一个networkx图
pos:dictionary 将节点作为键和位置作为值的字典。位置应该是长度为2的序列。
ax:Matplotlib Axes对象,可选,在指定的Matplotlib轴中绘制图形。
nodelist:list,可选,只绘制指定的节点(默认G.nodes())
node_size:标量或数组,节点大小(默认值= 300)。如果指定了数组,它必须是与点头长度相同。
node_color:颜色字符串或浮点数组,节点颜色。可以是单颜色格式字符串(default =‘r’),或者具有与点头相同长度的颜色序列。
如果指定了数值,它们将被映射到颜色使用cmap和vmin,vmax参数。看到matplotlib.scatter更多详细信息。
node_shape:string 节点的形状。规格为matplotlib.scatter 标记,‘so ^> v <dph8’(默认=‘o’)之一。
alpha:float 节点透明度(默认值= 1.0)
cmap:Matplotlib色图,色彩映射节点的强度(默认=无)
vmin,vmax:float 节点色彩映射缩放的最小值和最大值(默认值=无)
线宽:[无|标量|序列] 符号边框的线宽(默认值= 1.0)
label:[无|串] 图例的标签
‘’’

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

plt.figure(figsize = (12,9))

From = ['Food\nProduction', 'Transportation', 'Energy\nProduction',
        "Greenhouse\nGas\nEmissions",'Climate\nChange','Climate\nFeedbacks',
        'Greenhouse\nGas\nEmissions','Climate\nChange']
To = ["Greenhouse\nGas\nEmissions", "Greenhouse\nGas\nEmissions",
      "Greenhouse\nGas\nEmissions",'Climate\nChange','Climate\nFeedbacks',
      'Greenhouse\nGas\nEmissions','Climate\nChange','Everyone$^{Dies}$']

df = pd.DataFrame({
    'from':From, 'to':To})
# Define Node Positions
pos = {
   'Food\nProduction':(1,1),
       'Transportation':(1,2),
       'Energy\nProduction':(1,3),
       'Greenhouse\nGas\nEmissions':(2,2),
       'Climate\nChange':(3,2),
       'Climate\nFeedbacks':(2.5,3),
       'Everyone$^{Dies}$':(4,2)}

# Define Node Colors
NodeColors = {
   'Food\nProduction':[1,0,1],
              'Transportation':[1,1,0],
              'Energy\nProduction':[0,1,1],
              'Greenhouse\nGas\nEmissions':[1,.5,1],
              'Climate\nChange':[0,1,0],
              'Climate\nFeedbacks':[0,0,1],
              'Everyone$^{Dies}$':[1,0,0]}

Labels = {
   }
i = 0
for a in From:
    Labels[a]=a
    i +=1

Labels[To[-1]]=To[-1]

# Build your graph. Note that we use the DiGraph function to create the graph! This adds arrows
G=nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.DiGraph() )

# Define the colormap and set nodes to circles, but the last one to a triangle
Circles = []
Traingle = []
Colors = []
for n in G.nodes:
    if n != 'Everyone$^{Dies}$':
        Circles.append(n)
    else:
        Traingle.append(n)
    Colors.append(NodeColors[n])

# By making a white node that is larger, I can make the arrow "start" beyond the node
#draw_networkx_nodes(G, pos, nodelist, node_size, node_color, node_shape, alpha, cmap, vmin, vmax, ax, linewidths, edgecolors, label)
nodes = nx.draw_networkx_nodes(G, pos, nodelist = Circles, node_size=1.25e4, node_shape='o', node_color='red', alpha=1)
nodes = nx.draw_networkx_nodes(G, pos, nodelist = Circles, node_size=1e4, node_shape='o', node_color='blue',alpha=0.5)# , node_color=Colors,edgecolors='black',
nodes = nx.draw_networkx_nodes(G, pos, nodelist = Traingle, node_size=1.25e4, node_shape='>', node_color='green', alpha=1)
nodes = nx.draw_networkx_nodes(G, pos, nodelist = Traingle, node_size=1e4, node_shape='>', node_color="purple", alpha=0.5)# , node_color=Colors edgecolors='black',
nx.draw_networkx_labels(G, pos, Labels, font_size=12)

# Again by making the node_size larer, I can have the arrows end before they actually hit the node
edges = nx.draw_networkx_edges(G, pos, node_size=1.8e4, arrowstyle='->',width=2)

plt.xlim(0,4.5)
plt.ylim(0,4)
plt.axis('off')
plt.show()
import networkx as nx
G=nx.Graph()#创建空的简单图
#G=nx.DiGraph()#创建空的简单有向图
#G=nx.MultiGraph()#创建空的多图
#G=nx.MultiDiGraph()#创建空的有向多图
#加点、加边
G.add_node(1)#加1这个点
G.add_node(2)#加1这个点
G.add_node(3)#加1这个点
#G.add_node(1,1)#用(1,1)这个坐标加点 TypeError: add_node() takes 2 positional arguments but 3 were given
G.add_nodes_from([2,3])#加列表中的点
 
G.add_edge(1,2)#加边,起点是1终点是2
#G.add_weight_edge(1,2,3.0)#第三个是权值 AttributeError: 'Graph' object has no attribute 'add_weight_edge'
#G.add_edges_from(list)#添加列表中的边
#G.add_weight_edges_from(list)
#删除点和边的话
#G.remove_node()
#G.remove_nodes_from()
#G.remove_edge()
#G.remove_edges_from()
#G.clear()
#遍历点和边的话
#G.add_nodes_from([1,2,3])
#for n in G.nodes():
#    print(n)
#G.add_edges_from([(1,2),(1,3)])
#for e in G.edges():
#    print(e)
print(G.degree())
#[(1, 2), (2, 1), (3, 1)]#1这个点有两条边连着,2、3只有一条边连着
#画网络图,要用到matplotlib这个库了。
from matplotlib import pyplot as plt
import networkx as nx
G=nx.Graph()
G.add_nodes_from([1,2,3])
G.add_edges_from([(1,2),(1,3)])
nx.draw_networkx(G)
plt.show()
k_5=nx.complete_graph(5)#完全图
k_3_3=nx.complete_bipartite_graph(3,3)#完全二分图
nx.draw_networkx(k_5)
plt.show()
nx.draw_networkx(k_3_3)
plt.show()
# 无权无向图最短路径

from matplotlib import pyplot as plt
import networkx as nx
G=nx.path_graph(5)
path=nx.single_source_shortest_path(G,2)
length=nx.single_source_shortest_path_length(G,2)
print(path)
print(length)
nx.draw_networkx(G)
plt.show()
from matplotlib import pyplot as plt
import networkx as nx
G=nx.path_graph(5)
nx.draw_networkx(G)
plt.show()
from matplotlib import pyplot as plt
import networkx as nx
nodes=[0,1,2,3,4]
edges=[(0,1,10),(0,3,30),(0,4,100),(1,2,50),(2,3,20),(2,4,10),(3,4,60)]
G=nx.Graph()
G.add_nodes_from(nodes)
G.add_weighted_edges_from(edges)
path=nx.single_source_dijkstra_path(G,4)
length=nx.single_source_dijkstra_path_length(G,4)
print(path)
print(length)
nx.draw_networkx(G)
plt.show()
# encoding=utf-8
import matplotlib.pyplot as plt
from pylab import *                                 
#支持中文
mpl.rcParams['font.sans-serif'] = ['SimHei'] 
names = ['5', '10', '15', '20', '25']
x = range(len(names))
y = [0.855, 0.84, 0.835, 0.815, 0.81]
y1=[0.86,0.85,0.853,0.849,0.83]
#plt.plot(x, y, 'ro-')
#plt.plot(x, y1, 'bo-')
#pl.xlim(-1, 11)  # 限定横轴的范围
#pl.ylim(-1, 110)  # 限定纵轴的范围
plt.plot(x, y, marker='o', mec='r', mfc='w',label=u'y=x^2曲线图')
plt.plot(x, y1, marker='*', ms=10,label=u'y=x^3曲线图')
plt.legend()  
# 让图例生效
plt.xticks(x, names, rotation=45)
plt.margins(0)
plt.subplots_adjust
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值