为什么 Seaborn 调色板不适用于 Pandas 条形图?
Why does the Seaborn color palette not work for Pandas bar plots?
演示代码并显示颜色差异的在线 Jupyter 笔记本位于:
https://anaconda.org/walter/pandas_seaborn_color/notebook
当我使用 Pandas 数据框方法制作条形图时,颜色错误。 Seaborn 改进了 matplotlib 的调色板。 matplotlib 中的所有绘图都会自动使用新的 Seaborn 调色板。但是,来自 Pandas 数据帧的条形图恢复为非 Seaborn 颜色。此行为不一致,因为来自 Pandas 数据框 do 的线图使用 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()
这是 pandas 中的一个错误,专门用于条形图(我认为还有箱线图),已在 pandas master 中修复(参见报告的 issue and the PR 修复它).
这将在 pandas 0.18.0 中,将在未来几周内发布。
感谢@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))
df.plot(kind='bar', color=sns.color_palette())
我原来的回答:
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])
演示代码并显示颜色差异的在线 Jupyter 笔记本位于: https://anaconda.org/walter/pandas_seaborn_color/notebook
当我使用 Pandas 数据框方法制作条形图时,颜色错误。 Seaborn 改进了 matplotlib 的调色板。 matplotlib 中的所有绘图都会自动使用新的 Seaborn 调色板。但是,来自 Pandas 数据帧的条形图恢复为非 Seaborn 颜色。此行为不一致,因为来自 Pandas 数据框 do 的线图使用 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()
这是 pandas 中的一个错误,专门用于条形图(我认为还有箱线图),已在 pandas master 中修复(参见报告的 issue and the PR 修复它).
这将在 pandas 0.18.0 中,将在未来几周内发布。
感谢@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))
df.plot(kind='bar', color=sns.color_palette())
我原来的回答:
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])