【问题标题】:Seaborn color palette with Pandas groupby and .plot function带有 Pandas groupby 和 .plot 函数的 Seaborn 调色板
【发布时间】:2018-01-24 23:20:20
【问题描述】:

在尝试使用 seaborn 调色板绘制一些数据时,我遇到了一个非常令人沮丧的问题。我的工作流程是对我的数据框执行 groupby 操作,并使用如下代码将每个组绘制为自己的曲线:

import seaborn as sns; sns.set_style('whitegrid')
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(16, 6))

inner = d.groupby(['dr_min', 'dr_max'])
n = len(inner)
cmap = sns.color_palette("Blues", n_colors=n)
inner.plot(x='limit_l', y='lccdf', ax=ax1, color=cmap, legend=False)
inner.plot(x='limit_r', y='rcdf', ax=ax2, color=cmap, legend=False)

我希望看到我的每个 groupby 参数的曲线在颜色图中具有清晰的阴影,如下所示:

相反,我的曲线如下所示,根本没有颜色等级。谁能帮我理解为什么会这样?

【问题讨论】:

    标签: python pandas matplotlib plot seaborn


    【解决方案1】:

    您可能想要遍历 groupby 对象以选择每条线的颜色。

    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    import seaborn as sns
    
    a = np.tile(np.arange(0,10),5)
    b = np.linspace(0,1,len(a))
    c = np.repeat(list("ABCDE"), 10)
    df = pd.DataFrame({"x":a, "y":b, "c":c})
    
    fig, ax = plt.subplots()
    cmap = sns.color_palette("Blues", n_colors=5)
    
    inner = df.groupby(["c"])
    
    for i, (n, gr) in enumerate(inner):
        gr.plot(x="x", y="y", ax=ax, color=cmap[i])
    
    plt.show()
    

    【讨论】:

    • 这确实会正确生成曲线,但我认为这里不需要循环。这对我来说是一种解决方法。
    • pandas 未实现的功能的解决方法,是的。您可能会问为什么 pandas 没有实现为 color 参数提供多种颜色的选项。答案可能是这将使得有必要完全重写绘图函数,因为就像现在一样,color 只是在 matplotlib 线图上传递,而 matplotlib 中的 Line2D 对象只有一种与它。因此,有必要分别绘制多条曲线,循环是一种方便的方法。
    猜你喜欢
    • 2020-07-20
    • 1970-01-01
    • 2013-12-07
    • 2015-06-03
    • 2014-10-06
    • 2021-06-19
    • 2016-07-10
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多