我有一个代表numpy数组的变量x_axis
:
array(['administrator', 'retired', 'lawyer', 'none', 'student',
'technician', 'programmer', 'salesman', 'homemaker', 'executive',
'doctor', 'entertainment', 'marketing', 'writer', 'scientist',
'educator', 'healthcare', 'librarian', 'artist', 'other', 'engineer'],
dtype='|S13')
...我的y_axis
看起来像这样:
array([ 79, 14, 12, 9, 196, 27, 66, 12, 7, 32, 7, 18, 26,
45, 31, 95, 16, 51, 28, 105, 67])
当我尝试绘制它们时:
import matplotlib.pyplot as plt
plt.bar(x_axis,y_axis)
我收到错误:
TypeError: cannot concatenate 'str' and 'float' objects
注意:
我看过'类似'的问题,但没有具体询问有关matplotlib.bar的错误。
答案 0 :(得分:5)
这是因为bar
需要x坐标,但你的x_axis
是一个字符串数组。所以,bar
不知道在哪里绘制条形图。您需要的是以下内容:
import numpy as np
import matplotlib.pyplot as plt
y_axis = np.array([ 79, 14, 12, 9, 196, 27, 66, 12, 7, 32, 7, 18, 26,
45, 31, 95, 16, 51, 28, 105, 67])
x_labels = np.array(['administrator', 'retired', 'lawyer', 'none', 'student',
'technician', 'programmer', 'salesman', 'homemaker', 'executive',
'doctor', 'entertainment', 'marketing', 'writer', 'scientist',
'educator', 'healthcare', 'librarian', 'artist', 'other', 'engineer'],
dtype='|S13')
w = 3
nitems = len(y_axis)
x_axis = np.arange(0, nitems*w, w) # set up a array of x-coordinates
fig, ax = plt.subplots(1)
ax.bar(x_axis, y_axis, width=w, align='center')
ax.set_xticks(x_axis);
ax.set_xticklabels(x_labels, rotation=90);
plt.show()