python - 来自 NetworkX 度值的直方图 - Python 2 与 Python 3

标签 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

enter image description here

当我尝试在 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

我现在才开始弄乱 Python 3,使用我希望是非常简单的代码。有什么变化?

最佳答案

对于 Networkx 2.1,他们更改了 nx.degree(G) 的返回类型,它是一种名为 DegreeView 的不同类型,但是如果您进行简单的转换,绘图会好的

plt.hist(list(dict(nx.degree(G)).values()))
plt.show()

This is a histogram of Random Graph

关于python - 来自 NetworkX 度值的直方图 - Python 2 与 Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38885670/

相关文章:

python - Lex Bot 控制台上出现错误 - 在同一话语中第二次执行了履行 lambda

python - 使用 NetworkX 导出图形的布局位置

python - 在 NetworkX 的有向图中查找后继者的后继者

python - 绘制多条 3D 线 : data transformation

python - 即使在 jupyter notebook 中使用 plt.close(),如何防止 matplotlib 显示图形

Python简单的线性绘图

python - Networkx - 每个节点都是一个对象,如何根据对象属性进行标记和大小

python - 通过与另一个系列进行比较来查找数据框的索引值

python - 在 Python 中从 Enum 创建字典时,'float' 对象不可调用

python - 在 matplotlib 的图例中插入先前计算的值