python - 将颜色分配/映射到 Seaborn.regplot (Python 3) 中的点

标签 python pandas matplotlib seaborn

我有一个 seaborn 图,我想用颜色进行注释(最好用图例以及颜色映射)。我看到 regplot 有一个 color 方法。我不知道如何利用这个。

我尝试了几种不同的方法来设置我的方法,方法是为 color 方法提供一个映射 {index : color} 的字典,甚至将颜色值添加到数据框本身。

如何用我分配的颜色映射点?

np.random.seed(0)

# Create dataframe
DF_0 = pd.DataFrame(np.random.random((100,2)), columns=["x","y"])

# Label to colors
D_idx_color = {**dict(zip(range(0,25), ["#91FF61"]*25)),
               **dict(zip(range(25,50), ["#BA61FF"]*25)),
               **dict(zip(range(50,75), ["#91FF61"]*25)),
               **dict(zip(range(75,100), ["#BA61FF"]*25))}
DF_0["color"] = pd.Series(list(D_idx_color.values()), index=list(D_idx_color.keys()))

# Plot
sns.regplot(data=DF_0, x="x", y="y") #works, plot below

# sns.regplot(data=DF_0, x="x", y="y", color="color") # doesn't work
# ValueError: to_rgb: Invalid rgb arg "color"
# could not convert string to float: 'color'

# sns.regplot(data=DF_0, x="x", y="y", color=DF_0["color"]) # doesn't work
# ValueError: to_rgb: Invalid rgb arg "('#91FF61', '#91FF61', ...

# sns.regplot(data=DF_0, x="x", y="y", color=D_idx_color) # doesn't work
# ValueError: to_rgb: Invalid rgb arg "(0, 1, 2, ...

enter image description here

最佳答案

使用scatter_kws:

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns

np.random.seed(0)

# Create dataframe
DF_0 = pd.DataFrame(np.random.random((100,2)), columns=["x","y"])
DF_0['color'] =  ["#91FF61"]*25 + ["#BA61FF"]*25 + ["#91FF61"]*25 + ["#BA61FF"]*25
#print DF_0

sns.regplot(data=DF_0, x="x", y="y", scatter_kws={'c':DF_0['color']})
plt.show()

enter image description here

关于python - 将颜色分配/映射到 Seaborn.regplot (Python 3) 中的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38362573/

相关文章:

python - 为什么我不断收到模块 'azure' 未找到错误? [Azure IoT Edge 特定]

python - 为什么我不能在 Spyder 中使用 matplotlib.pyplot?

python - 具有大型数据集的 python 中的二维颜色和箭袋图

python - 如何防止屏幕上显示虚假消息

python - 如何保存文件夹和子文件夹中的音频文件(.wav)的频谱图?

python - 值错误: could not convert string to float: 'False' in python

pandas - 将 pandas 数据框中的多列拆分为行

python - Python matplotlib 中的 Axes.text() 和 Axes.annotate() 有什么区别

python - 需要帮助解决 Raspberry Pi 上 matplotlib 的性能问题

python - 在 Markdown 和 reStructuredText 中具有相同的 README