有没有一种方法可以根据不同列中的离散变量来制作matplotlib散点图标记或颜色? [英] Is there a way to make matplotlib scatter plot marker or color according to a discrete variable in a different column?

查看:121
本文介绍了有没有一种方法可以根据不同列中的离散变量来制作matplotlib散点图标记或颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib从DF中进行散点图绘制.为了获得每个数据集不同的颜色,我对plt.scatter进行了两个单独的调用:

I'm making scatterplots out of a DF using matplotlib. In order to get different colors for each data set, I'm making two separate calls to plt.scatter:

plt.scatter(zzz['HFmV'], zzz['LFmV'], label = dut_groups[0], color = 'r' )
plt.scatter(qqq['HFmV'], qqq['LFmV'], label = dut_groups[1], color = 'b' )
plt.legend()
plt.show()

这给了我所需的颜色依赖性,但实际上理想的是,如果我能让熊猫给我一个散布图,并在同一图上用类似

This gives me the desired color dependence but really what would be ideal is if I could just get pandas to give me the scatterplot with several datasets on the same plot by something like

df.plot(种类=散点图(x,y,颜色= df.Group,标记= df.Head)

df.plot(kind = scatter(x,y, color = df.Group, marker = df.Head)

显然没有这种动物(至少我能找到).因此,在我看来,下一个最好的事情是将plt.scatter调用放入一个循环中,在该循环中,我可以使颜色或标记根据其中一行(不是x或y,而是其他一些行)而变化.想要使用的是连续变量,看起来我可以使用色彩图,但是在我的情况下,我需要为此的行是一个字符串(变量的分类类型,而不是数字).

Apparently there is no such animal (at least that I could find). So, next best thing in my mind would be to put the plt.scatter calls into a loop where I could make the color or marker vary according to one of the rows (not x or y, but some other row. If the row I want to use were a continuous variable it looks like I could use a colormap, but in my case the row I need to sue for this is a string ( categorical type of variable, not a number).

任何帮助,不胜感激.

Any help much appreciated.

推荐答案

您所做的几乎可以,但是您必须传递color颜色向量,而不仅仅是变量向量.因此,您可以这样做:

What you're doing will almost work, but you have to pass color a vector of colors, not just a vector of variables. So you could do:

color = df.Group.map({dut_groups[0]: "r", dut_groups[1]: "b"})
plt.scatter(x, y, color=color)

标记样式相同

您还可以使用 seaborn 来按您期望的方式进行颜色映射(如在此处)中进行了讨论,尽管它不做标记样式映射:

You could also use seaborn to do the color-mapping the way you expect (as discussed here), although it doesn't do marker style mapping:

import seaborn as sns
import pandas as pd
from numpy.random import randn

data = pd.DataFrame(dict(x=randn(40), y=randn(40), g=["a", "b"] * 20))
sns.lmplot("x", "y", hue="g", data=data, fit_reg=False)

这篇关于有没有一种方法可以根据不同列中的离散变量来制作matplotlib散点图标记或颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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