使用 matplotlib 绘制条形图 - 类型错误

jxn*_*jxn 6 python plot matplotlib

我正在尝试绘制频率分布(单词的出现次数及其频率)

这是我的代码:

import matplotlib.pyplot as plt

y = [1,2,3,4,5]
x = ['apple', 'orange', 'pear', 'mango', 'peach']

plt.bar(x,y)
plt.show
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误:

TypeError: cannot concatenate 'str' and 'float' objects
Run Code Online (Sandbox Code Playgroud)

Mor*_*itz 6

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)
Run Code Online (Sandbox Code Playgroud)

如果有更好的方法将标签设置在条形的中间,那就很有趣了。

根据this 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)
Run Code Online (Sandbox Code Playgroud)