python - 来自 color dict python 的散点图图例
问题描述
对于df
以下内容,我正在尝试更改要显示legend
的值。scatter plot
Column 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
):
解决方案
推荐阅读
- javascript - 为什么,如果 WebAPI 操作方法返回一个 C# 列表,那么在 Javascript/Backbone 中会接收到一个对象而不是一个数组?
- php - 如何使用“管理区域”编写基于文本文件的留言簿?
- javascript - JQuery点击功能第一次不工作 - 需要2次点击才能正常工作
- python - 将字符串转换为频道 ID
- php - 如何使用 PHP pdo_oci 扩展连接到 Oracle 19c
- javascript - Strapi hit (post view) 计数器
- c++ - CMFCPropertyGridProperty 和线程
- python - 为什么 sklearn.metrics.confusion_matrix 和 sklearn.metrics.plot_confusion_matrix 函数定义不一致?
- python-3.x - 无法在 python 中从我的计算机中读取 csv(repl-it 和 aws cloud9)
- spreadsheet - 谷歌表格脚本:范围号不起作用