NetworkX度值的直方图-Python 2 vs.Python 3

Fom*_*ite 2 python matplotlib networkx

我有以下使用NetworkX在Python 2.7中工作的代码。基本上,它只是绘制度数节点的直方图,如下所示:

plt.hist(nx.degree(G).values())
plt.xlabel('Degree')
plt.ylabel('Number of Subjects')
plt.savefig('network_degree.png') #Save as file, format specified in argument
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

当我尝试在Python 3下运行相同的代码时,出现以下错误:

Traceback (most recent call last):
  File "filename.py", line 71, in <module>
    plt.hist(nx.degree(G).values())
  File "/Users/user/anaconda/envs/py3/lib/python3.5/site-packages/matplotlib/pyplot.py", line 2958, in hist
    stacked=stacked, data=data, **kwargs)
  File "/Users/user/anaconda/envs/py3/lib/python3.5/site-packages/matplotlib/__init__.py", line 1812, in inner
    return func(ax, *args, **kwargs)
  File "/Users/user/anaconda/envs/py3/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 5960, in hist
    x = _normalize_input(x, 'x')
  File "/Users/user/anaconda/envs/py3/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 5902, in _normalize_input
    "{ename} must be 1D or 2D".format(ename=ename))
ValueError: x must be 1D or 2D
Run Code Online (Sandbox Code Playgroud)

我现在刚刚开始使用我希望是非常简单的代码来搞混Python 3。有什么变化?

Ema*_*les 6

对于 Networkx 2.1,他们更改了 nx.degree(G) 的返回类型,它是一种不同的类型,称为degreeView,但是如果您进行简单的转换,则该图就可以了

plt.hist(list(dict(nx.degree(G)).values()))
plt.show()
Run Code Online (Sandbox Code Playgroud)

这是随机图的直方图


unu*_*tbu 5

在Python2中,该dict.values方法返回一个列表。在Python3中,它返回一个dict_values对象

In [197]: nx.degree(G).values()
Out[197]: dict_values([2, 2, 2, 2])
Run Code Online (Sandbox Code Playgroud)

由于plt.hist接受列表,但不接受dict_values对象,因此请将转换dict_values为列表:

  plt.hist(list(nx.degree(G).values()))
Run Code Online (Sandbox Code Playgroud)