python dictionary plot matplotlib

tan*_*aka 5 dictionary matplotlib python-3.x

I got I dictionary

lr = {'0': 0.1354364, '1': 0.134567, '2': 0.100000} 
Run Code Online (Sandbox Code Playgroud)

and so goes on.

I try ploting a simple line graph with key(0,1,2) as the x axis and the value (0.1354364,0.134567,0.100000) as the y value

plt.plot(lr.keys(),lr.values())
plt.title('ID model model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.savefig('ID modelo: model accuracy.png')
plt.clf()
Run Code Online (Sandbox Code Playgroud)

我得到了这个错误。

类型错误:float() 参数必须是字符串或数字,而不是“dict_keys”

Luc*_*ucG 7

这是因为,该方法keys()dict对象返回dict_keys其不受pyplot支持的对象。

我会将dict_keys对象转换list为使这项工作:

plt.plot(list(lr.keys()),list(lr.values()))
Run Code Online (Sandbox Code Playgroud)

正如@nikjohn 所提到的:

应该提到的是,这仅适用于 Python 3 环境。Python 2.7 和最新的 matplotlib 版本与问题中发布的代码完全一致。

  • @LucG - 应该提到的是,这仅适用于 Python 3 环境。Python 2.7 和最新的“matplotlib”版本与问题中发布的代码完全没问题。 (2认同)