对于下面的df
,我尝试更改legend
的{{1}}以显示scatter plot
的值。
当值是浮点型时它起作用,但是当我尝试插入字符串时,它返回ValueError。 Column C
ValueError: could not convert string to float: 'Y'
到目前为止,在尝试使用字符串时,我尝试将import pandas as pd
import matplotlib.pyplot as plt
d = ({
'A' : [1,2,3,4,5,6,7,8,9,10],
'B' : [1,1,1,2,2,2,7,7,7,7],
#'C' : ['X','Y','Z','X','Y','Z','A','X','Y','Z'], #Doesn't work
'C' : [2,4,6,8,2,4,6,8,10,2], # Works
})
df = pd.DataFrame(data=d)
fig,ax = plt.subplots()
x = df['A']
y = df['B']
classes = df['C']
unique = list(set(classes))
colors = [plt.cm.jet(float(i)/max(unique)) for i in unique]
for i, u in enumerate(unique):
xi = [x[j] for j in range(len(x)) if classes[j] == u]
yi = [y[j] for j in range(len(x)) if classes[j] == u]
plt.scatter(xi, yi, c=colors[i], label=str(u))
plt.legend()
更改为float
(如下所示):
str
它返回colors = [plt.cm.jet(float(i)/max(unique)) for i in unique]
colors = [plt.cm.jet(str(i)/max(unique)) for i in unique]
预期的输出(但我想在图例中包含字符串,所以用TypeError: unsupported operand type(s) for /: 'str' and 'str'
代替'X','Y','Z'
):