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()
You can build color palettes using the function sns. color_palette() . This function can take any of the Seaborn built-in palettes (see below). You can also build your own palettes by passing in a list of colors in any valid Matplotlib format, including RGB tuples, hex color codes, or HTML color names.
Seaborn provides a function called color_palette(), which can be used to give colors to plots and adding more aesthetic value to it.
palette attribute is used to set the color of the bars. It helps to distinguish between chunks of data.
The default color palette in seaborn is a qualitative palette with ten distinct hues: sns. color_palette() These colors have the same ordering as the default matplotlib color palette, "tab10" , but they are a bit less intense.
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))
df.plot(kind='bar', color=sns.color_palette())
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])
This was a bug in pandas specifically for bar plots (and boxplots as well I think), which is fixed in pandas master (see the reported issue and the PR to fix it).
This will be in pandas 0.18.0 which will be released in the coming weeks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With