我有一个基本的散点图,其中 x 和 y 是浮动的。但我想根据第三个分类变量更改标记的颜色。分类变量是字符串形式。这似乎引起了一个问题。
要使用 iris 数据集 - 这是我想我会使用的代码:
#Scatter of Petal
x=df['Petal Length']
y=df['Petal Width']
z=df['Species']
plt.scatter(x, y, c=z, s=15, cmap='hot')
plt.xlabel('Petal Width')
plt.ylabel('Petal Length')
plt.title('Petal Width vs Length')
但我收到一个错误:无法将字符串转换为浮点数:iris-setosa
在运行之前我是否必须将分类变量更改为数字变量,或者我可以对当前格式的数据做些什么?
Thanks
更新:整个回溯是:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-47-d67ee3bffc3b> in <module>()
3 y=df['Petal Width']
4 z=df['Species']
----> 5 plt.scatter(x, y, c=z, s=15, cmap='hot')
6 plt.xlabel('Petal Width')
7 plt.ylabel('Petal Length')
/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.pyc in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, hold, **kwargs)
3198 ret = ax.scatter(x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
3199 vmin=vmin, vmax=vmax, alpha=alpha,
-> 3200 linewidths=linewidths, verts=verts, **kwargs)
3201 draw_if_interactive()
3202 finally:
/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, **kwargs)
3605
3606 if c_is_stringy:
-> 3607 colors = mcolors.colorConverter.to_rgba_array(c, alpha)
3608 else:
3609 # The inherent ambiguity is resolved in favor of color
/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba_array(self, c, alpha)
420 result = np.zeros((nc, 4), dtype=np.float)
421 for i, cc in enumerate(c):
--> 422 result[i] = self.to_rgba(cc, alpha)
423 return result
424
/Users/mpgartland1/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba(self, arg, alpha)
374 except (TypeError, ValueError) as exc:
375 raise ValueError(
--> 376 'to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
377
378 def to_rgba_array(self, c, alpha=None):
ValueError: to_rgba: Invalid rgba arg "Iris-setosa"
to_rgb: Invalid rgb arg "Iris-setosa"
could not convert string to float: iris-setosa