b_kaufman
b_kaufman

Reputation: 71

Seaborn color palette with Pandas groupby and .plot function

I am having a very frustrating problem when trying to plot some data with a seaborn color palette. My workflow is to perform a groupby operation on my dataframe, and plot each group as its own curve using code like this:

import seaborn as sns; sns.set_style('whitegrid')
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(16, 6))

inner = d.groupby(['dr_min', 'dr_max'])
n = len(inner)
cmap = sns.color_palette("Blues", n_colors=n)
inner.plot(x='limit_l', y='lccdf', ax=ax1, color=cmap, legend=False)
inner.plot(x='limit_r', y='rcdf', ax=ax2, color=cmap, legend=False)

I expect to see a curve for each one of my groupby parameters with clear shades from the color map, as seen here: enter image description here

Instead, my curves look below, with no color grade at all. Can anyone help me understanding why this is happening?

enter image description here

Upvotes: 1

Views: 3674

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339102

Possibly you want to iterate over the groupby object to chose the color for each individual line.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

a = np.tile(np.arange(0,10),5)
b = np.linspace(0,1,len(a))
c = np.repeat(list("ABCDE"), 10)
df = pd.DataFrame({"x":a, "y":b, "c":c})

fig, ax = plt.subplots()
cmap = sns.color_palette("Blues", n_colors=5)

inner = df.groupby(["c"])

for i, (n, gr) in enumerate(inner):
    gr.plot(x="x", y="y", ax=ax, color=cmap[i])

plt.show()

enter image description here

Upvotes: 6

Related Questions