Pandas/Python/Matplotlib散点图标记的颜色取决于单元格中的值 [英] Pandas/Python/Matplotlib scatter plot markers colour depending on a value from a cell

查看:429
本文介绍了Pandas/Python/Matplotlib散点图标记的颜色取决于单元格中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找有关如何根据第三"列的值在散点图上设置点的解决方案.我找不到任何现成的解决方案,因此我已经构建了自己的解决方案,并且想与他人分享(也许有人会使用它):) 如果这不是发布它的地方,那么对不起,请删除它.

I have been searching for solution on how to set points on a scatter plot depending on the value of a 'third' column. I could not find any ready-made solution, thus I have constructed my own, and I want to share it (maybe someone will make a use of it) :) If this is not a place to post it, then I am sorry and please remove it.

让我们假设存在一个数据帧"scatterData",如下所示:

Lets assume that there is a data frame 'scatterData' as below:

    lad2014_name    Male    Female  Result
0   ABERDEEN CITY   95154   97421   -21.78
1   ABERDEENSHIRE   101875  105141  -13.10
2   ADUR    24047   26574   -16.16
3   ALLERDALE       38346   40192   -44.56
.
.
.
499 AMBER VALLEY    48720   51502   -3.56

我想在散点图上绘制男性和女性,但是我也想通过更改标记的颜色来显示结果"是负数还是正数.所以我做到了:

I want plot the Male and Female on a scatter plot, however I also want to show whether the 'Result' was negative or positive by changing the colour of the marker. So I have done this:

def resultColour(z):
    colour = '#e31a1c'
    if z > 0:
        colour = '#1f78b4'
    return colour

#Plotting the scatter plot
plt.figure(figsize=(12,10))

for index, row in scatterData.iterrows(): 
    x = row.Male
    z = row.Result
    y = row.Female
    t = resultColour(z)
    plt.scatter(x, y, c=t,s=85)
plt.xlabel('X axis lable',fontsize=15)
plt.ylabel('Y axis lable',fontsize=15)

plt.title('Plot title',fontsize=18)

plt.plot()

它会产生如下散点图

散点图

推荐答案

实际上,您可以为plt.scatter中的c关键字参数提供值的数组.它们将根据您可以使用cmap关键字设置的颜色映射表映射到标记颜色.

You can actually provide an array of values for the c keyword argument in plt.scatter. They will be mapped to marker colors according to a colormap that you can set with the cmap keyword.

示例:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm

np.random.seed(0)
df = pd.DataFrame({'x':np.random.randint(0,10,size=20),
                   'y':np.random.randint(0,10,size=20),
                   'z':np.random.uniform(-1,1,size=20)})

plt.figure(figsize=(5,5))
plt.scatter(df.x, df.y, c = df.z>0, cmap = cm.RdYlGn)

生产

cm模块具有很大的选择颜色图.如果您需要自己的确切颜色,则可以使用列出的颜色表,如下所示:

The cm module has a large selection of colormaps. If you need your own exact colors then you could use a listed colormap like this:

cmap = matplotlib.colors.ListedColormap(['#e31a1c','#1f78b4'])
plt.scatter(df.x, df.y, c = df.z>0, cmap = cmap)

这篇关于Pandas/Python/Matplotlib散点图标记的颜色取决于单元格中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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