我试图绘制一个频率分布(出现的词及其频率)
这是我的代码:
"The quick brown ${fox jumps ${over}} the lazy ${dog}."
但是,我收到了这个错误:
import matplotlib.pyplot as plt
y = [1,2,3,4,5]
x = ['apple', 'orange', 'pear', 'mango', 'peach']
plt.bar(x,y)
plt.show
答案 0 :(得分:3)
import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
x = np.arange(0,len(y)) + 0.75
xl = ['', 'apple', 'orange', 'pear', 'mango', 'peach']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5)
ax.set_xticklabels(xl)
ax.set_xlim(0,5.5)
如果有更好的方法将标签设置在条形图的中间,那将会很有趣。
根据这个SO post,有一个更好的解决方案:
import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
# adding 0.75 did the trick but only if I add a blank position to `xl`
x = np.arange(len(y))
xl = ['apple', 'orange', 'pear', 'mango', 'peach']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5, align='center')
ax.set_xticks(x)
ax.set_xticklabels(xl)
答案 1 :(得分:0)
只需添加两行:
import matplotlib.pyplot as plt
y = [1, 2, 3, 4, 5]
x_name = ['apple', 'orange', 'pear', 'mango', 'peach']
x = np.arange(len(x_name)) # <--
plt.bar(x, y)
plt.xticks(x, x_name) # <--
plt.show()
plt.bar(x_name, y)
将直接在<{1}}中支持<{1}},见https://github.com/matplotlib/matplotlib/issues/8959