Pandas – Why does the Seaborn color palette not work for Pandas bar plots

matplotlibpandasseaborn

An online Jupyter notebook demonstrating the code and showing the color differences is at:
https://anaconda.org/walter/pandas_seaborn_color/notebook

The colors are wrong when I make bar plots using Pandas dataframe method. Seaborn improves the color palette of matplotlib. All plots from matplotlib automatically use the new Seaborn palette. However, bar plots from Pandas dataframes revert to the non-Seaborn colors. This behavior is not consistent, because line plots from Pandas dataframes do use Seaborn colors. This makes my plots appear to be in different styles, even if I use Pandas for all my plots.

How can I plot using Pandas methods while getting a consistent Seaborn color palette?

I'm running this in python 2.7.11 using a conda environment with just the necessary packages for this code (pandas, matplotlib and seaborn).

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

df = pd.DataFrame({'y':[5,7,3,8]})

# matplotlib figure correctly uses Seaborn color palette
plt.figure()
plt.bar(df.index, df['y'])
plt.show()

# pandas bar plot reverts to default matplotlib color palette
df.plot(kind='bar')
plt.show()

# pandas line plots correctly use seaborn color palette 
df.plot()
plt.show()

Best Answer

Credit to @mwaskom for pointing to sns.color_palette(). I was looking for that but somehow I missed it hence the original mess with prop_cycle.


As a workaround you can set the color by hand. Note how the color keyword argument behaves differently if you are plotting one or several columns.

df = pd.DataFrame({'x': [3, 6, 1, 2], 'y':[5, 7, 3, 8]})

df['y'].plot(kind='bar', color=sns.color_palette(n_colors=1))

One column plot

df.plot(kind='bar', color=sns.color_palette())

Two columns plot

My original answer:

prop_cycle = plt.rcParams['axes.prop_cycle']
df['y'].plot(kind='bar', color=next(iter(prop_cycle))['color'])
df.plot(kind='bar', color=[x['color'] for x in prop_cycle])
Related Topic