Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dictionary plot matplotlib

I got I dictionary

lr = {'0': 0.1354364, '1': 0.134567, '2': 0.100000} 

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()

And I got this error.

TypeError: float() argument must be a string or a number, not 'dict_keys'

like image 632
tanaka Avatar asked Apr 15 '17 21:04

tanaka


People also ask

How do you display data from a dictionary in python?

values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list. If you use the type() method on the return value, you get “dict_values object”.

What does plot () do in Python?

The plot() function is used to draw points (markers) in a diagram. By default, the plot() function draws a line from point to point. The function takes parameters for specifying points in the diagram.


1 Answers

This is because the method keys() of dict objects returns a dict_keys object which is not supported by pyplot.

I would cast the dict_keys object into list to make this work:

plt.plot(list(lr.keys()),list(lr.values()))

As mentionned by @nikjohn:

It should be mentioned that this is only required for Python 3 environments. Python 2.7 and the latest matplotlib version, are perfectly okay with the code posted in the question.

like image 122
LucG Avatar answered Nov 11 '22 12:11

LucG