使用 seaborn.swarmplot 将数据点映射到颜色图 [英] Map data points to colormap with seaborn.swarmplot

查看:30
本文介绍了使用 seaborn.swarmplot 将数据点映射到颜色图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个seaborn.swarmplot,其中将单个数据点的颜色映射到颜色图.

我有一个与此类似的DataFrame:

  In [48]:df出[48]:a c 键0 1 12 第一1 4 35 第二2 5 12第二3 6 46 第一4 3 78 1st5 4 45第二6 5 34 1日7 6 70 第二

我使用以下代码生成了一个群图:

sns.swarmplot(x='Key', y = 'a', s=20, data = df)

并得到一个这样的情节:


带颜色条的解决方案

带颜色条的解决方案需要更多的工作.我们需要从 seaborn 调色板构建一个颜色图,标准化这个颜色图并创建一个颜色字典,对应于 df["c"] 数据框列中的各个颜色.然后我们再次使用 palette 关键字将这个字典提供给 swarmplot.

我们还需要删除自动生成但无用的图例,然后在绘图中创建一个新轴来放置颜色条.

将pandas导入为pd导入matplotlib.pyplot作为plt导入matplotlib.colorbar导入 matplotlib.colors导入 matplotlib.cm从 mpl_toolkits.axes_grid1 导入 make_axes_locatable将 seaborn 作为 sns 导入#重新创建数据框a = [1,4,5,6,3,4,5,6]c = [12,35,12,46,78,45,34,70]键= [1,2,2,1,1,2,1,2]key = ["{k} {a}".format(k = k,a = {1:"st",2:"nd"} [k])for key in k]df =pd.DataFrame({"a":a, "c":c, "Key":key})#从sns seagreen调色板创建一个matplotlib颜色图cmap = sns.light_palette("seagreen", reverse=False, as_cmap=True )# 归一化为来自 df["c"] 的可能值范围norm = matplotlib.colors.Normalize(vmin=df["c"].min(), vmax=df["c"].max())# 创建一个颜色字典(c 中的值:colormap 中的颜色)颜色= {}对于df ["c"]中的cval:颜色.更新({cval:cmap(norm(cval))})#创建一个图形fig = plt.figure(figsize=(5,2.8))#使用颜色字典作为调色板绘制图m = sns.swarmplot(x='Key', y = 'a', Hue="c", s=20, 数据 = df, 调色板 = 颜色)#删除图例,因为我们想设置一个颜色条plt.gca().legend_.remove()##创建颜色条##分频器 = make_axes_locatable(plt.gca())ax_cb =divider.new_horizo​​ntal(size="5%", pad=0.05)fig.add_axes(ax_cb)cb1 = matplotlib.colorbar.ColorbarBase(ax_cb,cmap = cmap,规范=规范,方向='垂直')cb1.set_label('某些单位')plt.show()

I would like to generate a seaborn.swarmplot, in which the color of single datapoints is mapped to a color map.

I have a DataFrame similar to this:

In[48]:df
Out[48]: 
      a  c   Key
   0  1  12  1st
   1  4  35  2nd
   2  5  12  2nd
   3  6  46  1st
   4  3  78  1st
   5  4  45  2nd
   6  5  34  1st
   7  6  70  2nd

I generate a swarmplot with the following code:

sns.swarmplot(x='Key', y = 'a',  s=20, data = df)

And get a plot like this:

Swarmplot

Now, I would like the datapoints to map to a colormap, which would represent the values according to column 'c' of the DataFrame.

I tried to add 'hue = 'c' to the code and get the following:

sns.swarmplot(x='Key', y = 'a',  hue='c',s=20, data = df)

Swarmplot with 'hue'

This kind of goes into the direction I want it, but I'd much rather prefer to have the color map to a color map, so that low 'c' values would for example be light-green and the higher the 'c' value get the darker the green gets.

As a legend I would like to have a gradient.

Help would be much appreciated!!!

解决方案

Solution without colorbar

The solution without colorbar is rather easy. You need to create a palette of colors (with as many colors as values) and supply it to the swarmplot using the palette argument.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
print sns.__version__ # swarmplot requires version 0.7.1

# Reconstruct the dataframe from the question (the hardest part)
a = [1,4,5,6,3,4,5,6]
c = [12,35,12,46,78,45,34,70]
key = [1,2,2,1,1,2,1,2]
key = ["{k}{a}".format(k=k, a={1:"st", 2:"nd"}[k]) for k in key]
df  =pd.DataFrame({"a":a, "c":c, "Key":key})

palette = sns.light_palette("seagreen", reverse=False,  n_colors=len(c) )
sns.swarmplot(x='Key', y = 'a',  hue='c',s=20, data = df, palette=palette)

plt.show()


Solution with colorbar

The solution with colorbar requires more work. We need to construct a colormap from the seaborn palette, normalize this colormap and create a dictionary of colors corresponding to the respective colors from the df["c"] dataframe column. We then provide this dictionary to the swarmplot using again the palette keyword.

We also need to remove the automatically generated, but useless legend and then create a new axes in the plot to place the colorbar.

import pandas as pd

import matplotlib.pyplot as plt
import matplotlib.colorbar
import matplotlib.colors
import matplotlib.cm
from mpl_toolkits.axes_grid1 import make_axes_locatable

import seaborn as sns

# recreate the dataframe
a = [1,4,5,6,3,4,5,6]
c = [12,35,12,46,78,45,34,70]
key = [1,2,2,1,1,2,1,2]
key = ["{k}{a}".format(k=k, a={1:"st", 2:"nd"}[k]) for k in key]
df  =pd.DataFrame({"a":a, "c":c, "Key":key})

#Create a matplotlib colormap from the sns seagreen color palette
cmap    = sns.light_palette("seagreen", reverse=False, as_cmap=True )
# Normalize to the range of possible values from df["c"]
norm = matplotlib.colors.Normalize(vmin=df["c"].min(), vmax=df["c"].max())
# create a color dictionary (value in c : color from colormap) 
colors = {}
for cval in df["c"]:
    colors.update({cval : cmap(norm(cval))})

#create a figure
fig = plt.figure(figsize=(5,2.8))
#plot the swarmplot with the colors dictionary as palette
m = sns.swarmplot(x='Key', y = 'a',  hue="c", s=20, data = df, palette = colors)
# remove the legend, because we want to set a colorbar instead
plt.gca().legend_.remove()

## create colorbar ##
divider = make_axes_locatable(plt.gca())
ax_cb = divider.new_horizontal(size="5%", pad=0.05)
fig.add_axes(ax_cb)
cb1 = matplotlib.colorbar.ColorbarBase(ax_cb, cmap=cmap,
                                norm=norm,
                                orientation='vertical')
cb1.set_label('Some Units')
plt.show()

这篇关于使用 seaborn.swarmplot 将数据点映射到颜色图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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