LdM
LdM

Reputation: 704

TypeErrors when I try to plot dict

I have a dict that I want to plot:

my_dict={'a': 0.015015015015015015,
 'b': 2.0,
 'c': 0.0,
 'd-e': 0.14,
 'f': 0.0
 nan: 0.06
}

This code is giving an error

import matplotlib.pylab as plt

lists = sorted(my_dict.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

-> TypeError: '<' not supported between instances of 'float' and 'str'

while this other

plt.bar(list(my_dict.keys()), list(my_dict.values()))

returns the error

-> TypeError: 'value' must be an instance of str or bytes, not a float

How can I plot it?

Upvotes: 0

Views: 86

Answers (1)

Camilo Mart&#237;nez M.
Camilo Mart&#237;nez M.

Reputation: 1565

The problem lies in the fact that plot expects numbers to plot. So you can just do

x, y = zip(*lists) # unpack a list of pairs into two tuples

x_num = np.arange(len(x)) # Numbers to plot

plt.plot(x_num, y)
plt.xticks(x_num, labels=x) # Replace x_num with your labels in x
plt.show()

And get

Plot

If there is a np.nan as a key in your dictionary, you can always replace it with another key that suits you best:

my_dict['not nan'] = my_dict.pop(np.nan) # Replace

# Plot
lists = sorted(my_dict.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.bar(list(my_dict.keys()), list(my_dict.values()))

And get

bar plot

Upvotes: 3

Related Questions