简体   繁体   English

在NetworkX中绘制图形

[英]Draw graph in NetworkX

I'm trying to draw any graph in NetworkX, but get nothing, not even errors: 我正在尝试在NetworkX中绘制任何图形,但什么都没有,甚至没有错误:

import networkx as nx
import matplotlib.pyplot as plt
g1=nx.petersen_graph()
nx.draw(g1)

Add to the end: 添加到最后:

plt.show()

import networkx as nx
import matplotlib.pyplot as plt
g1 = nx.petersen_graph()
nx.draw(g1)
plt.show()

When run from an interactive shell where plt.ion() has been called, the plt.show() is not needed. 从已调用plt.ion()的交互式shell运行时, plt.ion() plt.show() This is probably why it is omitted in a lot of examples. 这可能是很多例子中省略的原因。

If you run these commands from a script (where plt.ion() has not been called), the plt.show() is needed. 如果您从一个脚本(如果这些命令plt.ion()没有被调用),该plt.show()是必要的。 plt.ion() is okay for interactive sessions, but is not recommended for scripts . plt.ion()适用于交互式会话,但不建议用于脚本

in ipython notebook, just type in magic 在ipython笔记本中,只需输入魔法

%matplotlib inline

or 要么

%matplotlib notebook

You can easily plot with networkx graphs using jupyter notebook. 您可以使用jupyter notebook轻松地使用networkx图进行绘图。 See first example. 见第一个例子。

OR, you can use Bokeh to plot graphs, which adds useful features. 或者,您可以使用Bokeh绘制图表,这会添加有用的功能。 The package holoviews makes it even simpler to plot a graphs with bokeh. 包装holoviews使绘制带有散景的图形变得更加简单。 It adds features like automatic highlighting and show of labels while hovering over nodes. 它在鼠标悬停在节点上时添加了自动突出显示和标签显示等功能。 However, editing colors etc. seems to be an issue. 但是,编辑颜色等似乎是一个问题。

%pylab inline  
# `pylab notebook`  # for interactive plots

import pandas as pd
import networkx as nx
import holoviews as hv

G=nx.Graph()
ndxs = [1,2,3,4]
G.add_nodes_from(ndxs)
G.add_weighted_edges_from( [(1,2,0), (1,3,1) , (1,4,-1) , (2,4,1) , (2,3,-1), (3,4,10) ] ) 
nx.draw(G, nx.spring_layout(G, random_state=100))

在此输入图像描述

And here the example with bokeh and holoview: 这里有散景和全息视图的例子:

hv.extension('bokeh')
%opts Graph [width=400 height=400]
padding = dict(x=(-1.1, 1.1), y=(-1.1, 1.1))
hv.Graph.from_networkx(G, nx.layout.spring_layout).redim.range(**padding)

在此输入图像描述

You should give it a try and plot it in your notebook to see the difference. 您应该尝试一下并将其绘制在笔记本中以查看差异。

It works fine by adding: 它添加以下工作正常:

import matplotlib.pyplot as plt
plt.show()

to your code. 你的代码。 mine worked fine. 我工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM