[英]TypeErrors when I try to plot dict
I have a dict that I want to plot:我有一个我想要 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'
-> TypeError: 'float' 和 '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
-> TypeError: 'value' 必须是 str 或 bytes 的实例,而不是浮点数
How can I plot it?我怎么能plot呢?
The problem lies in the fact that plot
expects numbers to plot.问题在于
plot
期望数字为 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并得到
If there is a np.nan
as a key in your dictionary, you can always replace it with another key that suits you best:如果你的字典中有一个
np.nan
作为键,你总是可以用另一个最适合你的键来替换它:
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并得到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.