如何在matplotlib模块中应用seaborn.scatterplot(样式)?

2024-06-02 05:36:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用matplotlib模块绘制此图。我可以制作x、y图例,但我不知道如何在matplotlib模块中应用seaborn.scatterplot(样式)。有人能帮我吗?我怎样才能画出这个情节

下面的绘图代码如下所示:

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)

enter image description here

这就是我要写的代码

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

enter image description here


Tags: 模块代码importsignalmatplotlibaspltseaborn
2条回答

重塑海生情节

  • 将每个特征分离为一个数据框,并使用所选的标记和颜色绘制该数据框
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()

enter image description here

groupby绘图

  • ^{}'region'上,然后绘图
  • 这可能是最简单的方法,没有seaborn
    • 最简单的方法是不需要手动创建每个数据子集
  • 每个regionevent按字母顺序绘制,这就是为什么cmap用于指定颜色
  • 因为blue(C0)是第二个绘制的(在顶部),所以它看起来像主色
  • 我添加了s(大小)和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()

enter image description here

使用seaborn

  • 不使用seaborn是没有意义的,因为seaborn只是matplotlib的高级API
  • 从配置意义上讲,您想通过matplotlib执行的任何操作,也可以通过相同或类似的方法对seaborn图执行。
    • 例如为legend创建自定义Patch
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)

enter image description here

使用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)

enter image description here

我不确定您为什么要使用matplotlib来重现这一点,但我使用seaborn的数据来绘制matplotlib中的两个参数。我需要使用相同的技术添加其他两个参数

import matplotlib.pyplot as plt
import seaborn as sns

fmri = sns.load_dataset('fmri')

plt.style.use('seaborn-notebook')

fig, ax = plt.subplots()

ax.scatter(x = fmri.loc[fmri['region'] == 'parietal',
                        ['timepoint']], y = fmri.loc[fmri['region'] == 'parietal',['signal']],
                        s = 15, label='parietal', marker='o')
ax.scatter(x = fmri.loc[fmri['region'] == 'parietal', 
                        ['timepoint']], y = fmri.loc[fmri['region'] == 'frontal',['signal']],
                        s = 15, label='frontal', marker='o')

plt.xlabel('timepoint')
plt.ylabel('signal')

ax.legend(title='region')

plt.show()

enter image description here

相关问题 更多 >