为什么Seaborn调色板不能用于Pandas条形图?

Wal*_*ter 6 matplotlib pandas seaborn

在线Jupyter笔记本演示代码并显示颜色差异,请访问:https://anaconda.org/walter/pandas_seaborn_color/notebook

当我使用Pandas数据帧方法制作条形图时,颜色是错误的.Seaborn改善了matplotlib的调色板.matplotlib的所有图表都会自动使用新的Seaborn调色板.但是,Pandas数据帧的条形图恢复为非Seaborn颜色.此行为不一致,因为来自Pandas数据帧的线图确实使用了Seaborn颜色.这使我的情节看起来有不同的风格,即使我将Pandas用于我的所有情节.

如何在获得一致的Seaborn调色板的同时使用Pandas方法进行绘图?

我在python 2.7.11中使用conda环境运行它,只需要这个代码的必要包(pandas,matplotlib和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()
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 7

感谢@mwaskom指向sns.color_palette().我正在寻找那个,但不知何故,我错过了它因此原来一团糟prop_cycle.


作为解决方法,您可以手动设置颜色.请注意,color如果要绘制一个或多个列,关键字参数的行为方式会有所不同.

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))
Run Code Online (Sandbox Code Playgroud)

一栏情节

df.plot(kind='bar', color=sns.color_palette())
Run Code Online (Sandbox Code Playgroud)

两列情节

我的原始答案:

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])
Run Code Online (Sandbox Code Playgroud)