Search code examples
pythonpandasmatplotlibcolorsseaborn

How to sync Colors across Subplots of different types


I am trying to create a subplot with two plots. The first plot is essentially a scatter plot (i'm using regplot) and the second is a histogram.

my code is as follows:

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

data = {'source':['B1','B1','B1','C2','C2','C2'],
        'depth':[1,4,9,1,3,10],
        'value':[10,4,23,78,24,45]}

df = pd.DataFrame(data)

f, (ax1, ax2) = plt.subplots(1,2)

for source in df['source'].unique():
    
    x = df.loc[df['source'] == source, 'value']
    y = df.loc[df['source'] == source, 'depth']
    
    sns.regplot(x,
                y,
                scatter = True,
                fit_reg = False,
                label = source,
                ax = ax1)
    ax1.legend()
    
    sns.distplot(x,
                 bins = 'auto',
                 norm_hist =True,
                 kde = True,
                 rug = True,
                 ax = ax2,
                 label = source)
    ax2.legend()
    ax2.relim()
    ax2.autoscale_view()
plt.show()

The result is shown below.

enter image description here

As you can see, the colors between the scatter and the histogram are different. Now, I had a play around with color pallets and all, which has not worked. Can anyone shed any light on how I can sync the colors?


Solution

  • Use color argument of plotting functions. In this example from current seaborn color palette in your for cycle with itertools.cyclecolors to plot are selected one by one:

    import pandas as pd 
    import matplotlib.pyplot as plt 
    import seaborn as sns 
    import itertools
        
    data = {'source':['B1','B1','B1','C2','C2','C2'],
            'depth':[1,4,9,1,3,10],
            'value':[10,4,23,78,24,45]}
    
    df = pd.DataFrame(data)
    
    f, (ax1, ax2) = plt.subplots(1,2)
    
    # set palette 
    palette = itertools.cycle(sns.color_palette())
    
    # plotting 
    for source in df['source'].unique():
    
        x = df.loc[df['source'] == source, 'value']
        y = df.loc[df['source'] == source, 'depth']
    
        # color
        c = next(palette)
        sns.regplot(x,
                    y,
                    scatter = True,
                    fit_reg = False,
                    label = source,
                    ax = ax1,
                    color=c)
        ax1.legend()
    
        sns.distplot(x,
                     bins = 'auto',
                     norm_hist =True,
                     kde = True,
                     rug = True,
                     ax = ax2,
                     label = source,
                     color=c)
        ax2.legend()
        ax2.relim()
        ax2.autoscale_view()
    
    plt.show()
    

    enter image description here

    You can set your own color palette like in this answer