김준석
김준석

Reputation: 57

How can I apply seaborn.scatterplot(style) in matplotlib module?

I'm trying to make this plot just use matplotlib module. I can make x, y legends but I have no idea how can I apply seaborn.scatterplot(style) in matplotlib module. Can anyone help me how can I make this plot??

The under plot code is this:

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

And This is what I'm trying to make code

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

Upvotes: 1

Views: 1540

Answers (2)

Trenton McKinney
Trenton McKinney

Reputation: 62523

Recreating the Seaborn Plot

  • Separate each feature into a dataframe and plot that dataframe with the marker and color of choice
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

Plot from groupby

  • pandas.DataFrame.groupby on 'region' and then plot.
  • This is probably the easiest way, without seaborn
    • Easiest in that manually creating each subset of data isn't required.
  • Each region and event is plotted in alphabetical order, which is why cmap is used to specify the color.
  • Since blue (C0) is plotted second (on top), it looks like the dominant color.
  • I've added s (size), and alpha, which can be removed, or changed as needed.
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

Use seaborn

  • It doesn't make sense, not to use seaborn, because seaborn is just a high-level API for matplotlib.
  • Anything you want to do, from a configuration sense, with matplotlib, can also be done to the seaborn figure, with the same, or similar methods.
    • Such as creating a custom Patch for the legend.
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

Using seaborn.stripplot

  • Since there is so much overlapping data, I think the best plot option, in this case, is the 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

Upvotes: 3

r-beginners
r-beginners

Reputation: 35240

I'm not sure why you want to reproduce this using matplotlib, but I used seaborn's data to graph the two parameters in matplotlib. I need to add the other two parameters using the same technique.

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

Upvotes: 1

Related Questions