Soerendip
Soerendip

Reputation: 9184

How to plot with different palettes in subplots of the same figure?

How can I plot with different palettes in subplots of the same figure? In the example below, the generation of the plots is delayed. So, only the last palette is used to generate plots. Though I need the subplots generated with a different palettes.

x = np.arange(10)
pal = sns.color_palette("rainbow", 12)
sns.set_palette(pal)

subplot(2, 1, 1)
for i in range(4):
    plot(x, i*np.sin(x))

subplot(2, 1, 2)

pal = sns.color_palette("Set1", 12)
sns.set_palette(pal)

for i in range(4):
    plot(x, i*np.cos(x))

tight_layout()

enter image description here

Upvotes: 1

Views: 2966

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339765

You need to set the palette before creating the subplot. This is because the color cycle is a property of the axes. The axes will take the current property cycler from the rcParams at creation time. So set_palette, which changes the property cycler, needs to be called beforehand.

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

x = np.arange(10)

# First subplot
pal1 = sns.color_palette("rainbow", 12)
sns.set_palette(pal1)

plt.subplot(2, 1, 1)
for i in range(4):
    plt.plot(x, i*np.sin(x))

# Second subplot
pal2 = sns.color_palette("Set1", 12)
sns.set_palette(pal2)

plt.subplot(2, 1, 2)
for i in range(4):
    plt.plot(x, i*np.cos(x))

plt.tight_layout()
plt.show()

enter image description here

Upvotes: 1

Related Questions