我有一个x_axis表示numpy数组的变量:
array(['administrator', 'retired', 'lawyer', 'none', 'student',
'technician', 'programmer', 'salesman', 'homemaker', 'executive',
'doctor', 'entertainment', 'marketing', 'writer', 'scientist',
'educator', 'healthcare', 'librarian', 'artist', 'other', 'engineer'],
dtype='|S13')
Run Code Online (Sandbox Code Playgroud)
......我的y_axis样子如下:
array([ 79, 14, 12, 9, 196, 27, 66, 12, 7, 32, 7, 18, 26,
45, 31, 95, 16, 51, 28, 105, 67])
Run Code Online (Sandbox Code Playgroud)
当我试图绘制它们时:
import matplotlib.pyplot as plt
plt.bar(x_axis,y_axis)
Run Code Online (Sandbox Code Playgroud)
我收到错误:
TypeError: cannot concatenate 'str' and 'float' objects
Run Code Online (Sandbox Code Playgroud)
注意:
我看过'类似'的问题,但没有特别询问matplotlib.bar中的这个错误.
那是因为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()
Run Code Online (Sandbox Code Playgroud)