大 pandas -每个点都有不同的颜色图例的散点图 [英] pandas - scatter plot with different color legend for each point

查看:113
本文介绍了大 pandas -每个点都有不同的颜色图例的散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从以下示例开始:

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)

我得到的是以下散点图:

what I obtained is the following scatterplot:

我现在正尝试为这四个点分别设置不同的颜色.我知道我可以在列表中循环显示例如4种颜色,例如:

I'm now trying to set a different color for each of the four points. I know that I can loop over a set of, for instance, 4 colors in a list like:

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

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

but since my real dataset comprise at least 20 different points, I was looking for a sort of "color generator" to loop within it.

推荐答案

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

The following method will create a list of colors as long as your dataframe, and then plot a point with a label with each color:

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()

这篇关于大 pandas -每个点都有不同的颜色图例的散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆