首页 > 解决方案 > 如何在 matplotlib 模块中应用 seaborn.scatterplot(style)?

问题描述

我试图让这个情节只使用 matplotlib 模块。我可以制作 x,y 图例,但我不知道如何在 matplotlib 模块中应用 seaborn.scatterplot(style)。谁能帮助我如何制作这个情节?

下面的情节代码是这样的:

import matplotlib.pyplot as plt
import seaborn as sns

fmri = sns.load_dataset('fmri')

fmri.head()

sns.scatterplot(x = 'timepoint', y = 'signal', hue = 'region', style = 'event', data = fmri)

在此处输入图像描述

这就是我要编写的代码

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches 

fig, ax = plt.subplots()

colors = {'parietal' : 'tab:blue', 'frontal' : 'orange'}

scatter = ax.scatter(x = fmri['timepoint'],y = fmri['signal'],c = fmri['region'].apply(lambda x: colors[x]),s = 15)

parietal = mpatches.Patch(color = 'tab:blue',label = 'parietal')

frontal = mpatches.Patch(color = 'orange',
                         label = 'frontal')

plt.xlabel('timepoint')

plt.ylabel('signal')

plt.legend(handles = [parietal, frontal])

在此处输入图像描述

标签: pythonpandasmatplotlibseaborn

解决方案


重新创建 Seaborn 情节

  • 将每个特征分成一个数据框,并用选择的标记和颜色绘制该数据框
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# load the data set
fmri = sns.load_dataset('fmri')

# create separate dataframe for each group of data
fc = fmri[(fmri.region == 'frontal') & (fmri.event == 'cue')]
fs = fmri[(fmri.region == 'frontal') & (fmri.event == 'stim')]
pc = fmri[(fmri.region == 'parietal') & (fmri.event == 'cue')]
ps = fmri[(fmri.region == 'parietal') & (fmri.event == 'stim')]

# create a list with the data, color, marker and label
dfl = [(ps, 'C0', 'o', 'Parietal: Stim'), (pc, 'C0', 'x', 'Parietal: Cue'),
       (fs, 'C1', 'o', 'Frontal: Stim'), (fc, 'C1', 'x', 'Frontal: Cue')]

# plot
plt.figure(figsize=(10, 7))
for data, color, marker, label in dfl:
    plt.scatter('timepoint', 'signal', data=data, color=color, marker=marker, label=label)

plt.legend(title='Region: Event')
plt.xlabel('timepoint')
plt.ylabel('signal')
plt.show()

在此处输入图像描述

情节从groupby

  • pandas.DataFrame.groupby'region'然后情节。
  • 这可能是最简单的方法,没有seaborn
    • 最简单的是不需要手动创建每个数据子集。
  • 每个regionevent都按字母顺序绘制,这就是为什么cmap用于指定颜色的原因。
  • 由于blue(C0) 被绘制在第二个(在顶部),它看起来像是主色。
  • 我添加了s(size) 和alpha, 可以根据需要删除或更改。
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# load the data set
fmri = sns.load_dataset('fmri')

# map for color and marker
pmap = {'parietal_cue': ['C0', 'x'], 'parietal_stim': ['C0', 'o'], 'frontal_cue': ['C1', 'x'], 'frontal_stim': ['C1', 'o']}

# Groupby and plot
plt.figure(figsize=(10, 7))
for g, df in fmri.groupby(['region', 'event']):
    
    # get values from dict for group g
    maps = pmap[f'{g[0]}_{g[1]}']
    
    plt.scatter('timepoint', 'signal', data=df, c=maps[0], marker=maps[1], s=15, alpha=0.5, label=f'{g[0]}: {g[1]}')

plt.legend(title='Region: Event')
plt.xlabel('timepoint')
plt.ylabel('signal')
plt.show()

在此处输入图像描述

采用seaborn

  • 没有意义,不要使用seaborn,因为seaborn只是matplotlib.
  • 任何你想做的事情,从配置意义上来说,用matplotlib, 也可以对seaborn图形做,用相同或类似的方法。
    • 例如Patchlegend.
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

plt.figure(figsize=(10, 7))
p = sns.scatterplot(x='timepoint', y='signal', hue='region', data=fmri)

# get legend handle and labels
h, l = p.get_legend_handles_labels()

# create a new patch
patches = [Patch(color=k.get_fc()[0], label=v) for k, v in list(zip(h, l))]

# add the legend
plt.legend(handles=patches)

在此处输入图像描述

使用seaborn.stripplot

  • 由于有太多重叠的数据,我认为在这种情况下,最好的绘图选项是seaborn.stripplot.
plt.figure(figsize=(12, 7))
sns.stripplot(x='timepoint', y='signal', hue='region', s=4, alpha=0.6, jitter=True, data=fmri)

在此处输入图像描述


推荐阅读