python - 使用 seaborn.swarmplot 将数据点映射到颜色图

标签 python pandas matplotlib seaborn

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

我有一个类似这样的 DataFrame:

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

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

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

然后得到这样的情节:

Swarmplot

现在,我希望将数据点映射到颜色图,该颜色图将表示根据 DataFrame 的“c”列的值。

我尝试将 'hue = 'c' 添加到代码中并得到以下内容:

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

Swarmplot with 'hue'

这会进入我想要的方向,但我更喜欢将颜色映射到颜色映射,这样低的“c”值例如会是浅绿色,而“c'值越深,绿色越深。

作为一个传说,我想要一个渐变。

帮助将不胜感激!!!

最佳答案

没有颜色条的解决方案

没有颜色条的解决方案相当简单。您需要创建一个 palette颜色(颜色与值一样多)并将其提供给 swarmplot使用 palette争论。

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

enter image description here


颜色条解决方案

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

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

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

enter image description here

关于python - 使用 seaborn.swarmplot 将数据点映射到颜色图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40814612/

相关文章:

python - 间距不规则的条形图

python - 替换文件中的多个正则表达式字符串匹配项

Python MySQL数据库,数据更新错误?

python - 将 .pyw 转换为 .exe

python - 获取 pandas groupby 中组的所有值

python - 如何在Python中将直线方程添加到绘图上

python - Mongodb 查找结果错误的 Int64 对象

python - 时间序列数据的 Django 数据库结构?

python - 用另一列中的元素替换数据框中的列 - python

python - 有什么方法可以使 matplotlib 的 Nbagg 后端更快,或者 Inline 后端更高分辨率?