首页 > 解决方案 > 来自 color dict python 的散点图图例

问题描述

对于df以下内容,我正在尝试更改要显示legend的值。scatter plotColumn C

当值是浮点数时它可以工作,但是当我尝试插入字符串时它会返回一个 ValueError。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'不是2,4,6):

在此处输入图像描述

标签: pythonmatplotliblegendscatter

解决方案


推荐阅读