2016-08-11 32 views
0

我有以下代碼,它使用NetworkX在Python 2.7中工作。基本上,它只是繪製度節點像這樣的直方圖:來自NetworkX Degree Values的直方圖 - Python 2與Python 3

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,使用我希望的代碼非常簡單。什麼改變了?

+0

支持字典視圖只是合併掌握的https: //github.com/matplotlib/matplotlib/pull/6787 – tacaswell

回答

3

在Python2中,dict.values方法返回一個列表。 在Python3,它返回a dict_values object

In [197]: nx.degree(G).values() 
Out[197]: dict_values([2, 2, 2, 2]) 

由於plt.hist接受一個列表,而不是dict_values對象,轉換dict_values到一個列表:

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