Python 无法使用灵活类型plt.hist执行reduce
我有一个包含1000个元素及其各自频率的数据集。我需要绘制前10个出现元素的柱状图。Python 无法使用灵活类型plt.hist执行reduce,python,text,matplotlib,word-frequency,Python,Text,Matplotlib,Word Frequency,我有一个包含1000个元素及其各自频率的数据集。我需要绘制前10个出现元素的柱状图。 我做到了: 得到了这个错误: TypeError Traceback (most recent call last) <ipython-input-29-ff974b3a2354> in <module>() 5 print top_words[:10] 6 ---->
我做到了: 得到了这个错误:
TypeError
Traceback (most recent call last)
<ipython-input-29-ff974b3a2354> in <module>()
5 print top_words[:10]
6
----> 7 plt.hist(top_words_10)
C:\Anaconda\lib\site-packages\numpy\core\_methods.pyc in _amin(a, axis, out, keepdims)
12 def _amin(a, axis=None, out=None, keepdims=False):
13 return um.minimum.reduce(a, axis=axis,
---> 14 out=out, keepdims=keepdims)
15
16 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
TypeError: cannot perform reduce with flexible type
问题是
plt.hist
试图使用nmupy.hist
根据传入的数据生成直方图
您只需要使用bar
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
words, counts = zip(*data32) # unpack pairs into two lists
ax.bar(range(len(counts)), words, align='center')
ax.set_xticks(range(len(counts))
ax.set_xticklabels(words) # this is about the _only_ use for set_xticklabels
plt.draw
请参阅和。由于需要将数据转换为数字类型,因此会出现此错误。数组包含字符串
import matplotlib.pyplot as plt
import numpy as np
data = [(' whitefield', 65299), (' bellandur', 57061), (' kundalahalli', 51769), (' marathahalli', 50639),
(' electronic city', 44041), (' sarjapur road junction', 34164), (' indiranagar 2nd stage', 32459),
(' malleswaram', 32171), (' yelahanka main road', 28901), (' domlur', 28869)]
freequency = []
words = []
for line in data:
freequency.append(line[1])
words.append(line[0])
y_axis = np.arange(1, len(words) + 1, 1)
plt.barh(y_axis, freequency, align='center')
plt.yticks(y_axis, words)
plt.show()
thanx一吨..真是太棒了。。我怎样才能交换轴线???我想要垂直的。。请解释for循环,看看这个答案。在for循环中,我只是通过元组解析列表:
('whitefield',65299)
,通过索引获取元素并将它们存储在列表中。应该有一些图表将分类值列表作为输入并绘制计数。这应该是开箱即用的,它是人们能想象到的最简单的图表。嗨..thnx但我得到了一个错误文件“”,第6行ax.setxticklabels(words)#这是关于setxticklabels^ SyntaxError:无效的syntax它缺失在哪里??对不起,我是新手,所以所有这些都是第一个tym;)在集合中。学习有效地调试是学习编程时最重要的技能。语法错误很好,它们会在几行中告诉您它们要处理的位置。
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
words, counts = zip(*data32) # unpack pairs into two lists
ax.bar(range(len(counts)), words, align='center')
ax.set_xticks(range(len(counts))
ax.set_xticklabels(words) # this is about the _only_ use for set_xticklabels
plt.draw
import matplotlib.pyplot as plt
import numpy as np
data = [(' whitefield', 65299), (' bellandur', 57061), (' kundalahalli', 51769), (' marathahalli', 50639),
(' electronic city', 44041), (' sarjapur road junction', 34164), (' indiranagar 2nd stage', 32459),
(' malleswaram', 32171), (' yelahanka main road', 28901), (' domlur', 28869)]
freequency = []
words = []
for line in data:
freequency.append(line[1])
words.append(line[0])
y_axis = np.arange(1, len(words) + 1, 1)
plt.barh(y_axis, freequency, align='center')
plt.yticks(y_axis, words)
plt.show()