gpt4 book ai didi

python - Pandas - 每个点具有不同颜色图例的散点图

转载 作者:太空狗 更新时间:2023-10-30 02:02:53 37 4
gpt4 key购买 nike

从下面的例子开始:

fig, ax = plt.subplots()

df = pd.DataFrame({'n1':[1,2,1,3], 'n2':[1,3,2,1], 'l':['a','b','c','d']})

for label in df['l']:

df.plot('n1','n2', kind='scatter', ax=ax, s=50, linewidth=0.1, label=label)

我得到的是下面的散点图:

enter image description here

我现在正在尝试为四个点中的每一个设置不同的颜色。我知道我可以遍历一组,例如,列表中的 4 种颜色:

colorlist = ['b','r','c','y']

但由于我的真实数据集包含至少 20 个不同的点,我一直在寻找一种“颜色生成器”在其中循环。

最佳答案

以下方法将创建一个与数据框一样长的颜色列表,然后绘制一个带有每种颜色标签的点:

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as colors
import numpy as np
import pandas as pd

fig, ax = plt.subplots()

df = pd.DataFrame({'n1':[1,2,1,3], 'n2':[1,3,2,1], 'l':['a','b','c','d']})

colormap = cm.viridis
colorlist = [colors.rgb2hex(colormap(i)) for i in np.linspace(0, 0.9, len(df['l']))]

for i,c in enumerate(colorlist):

x = df['n1'][i]
y = df['n2'][i]
l = df['l'][i]

ax.scatter(x, y, label=l, s=50, linewidth=0.1, c=c)

ax.legend()

plt.show()

enter image description here

关于python - Pandas - 每个点具有不同颜色图例的散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37812325/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com