如何在Seaborn regplot中自动替换或循环线型?

时间:2019-04-01 18:58:59

标签: python-3.x matplotlib seaborn

我希望我在同一张图表上的21条数据行可以通过图例得到更好的解释。例如,也许我可以使其他所有图例条目/行用破折号而不是连续的行显示。我对Seaborn和Matplotlib的混合使用使我感到困惑-我不确定如何交替使用破折号。

products = list(data_cleaned.columns)
print('products: \n',products)
for i, product in enumerate(products):
    subset = data_cleaned[data_cleaned[product]>0][product]
    sns.distplot(subset,hist=False,kde=True,kde_kws={'linewidth':3},label=product)
    if i%2 == 0:
        plt.plot(subset,'-', dashes = [8, 4, 2, 4, 2, 4])

sns.set(rc = {'figure.figsize':(25,10)})
#sns.palplot()
palette_to_use = sns.color_palette("hls", 21)
sns.set_palette(palette_to_use)
#cmap = ListedColormap(sns.color_palette().as_hex())
plt.legend(prop={'size': 16}, title = 'Product')
plt.title('Density Plot with Multiple Products')
plt.xlabel('log10 of monthly spend')
plt.ylabel('Density')

这是我当前的输出: enter image description here

2 个答案:

答案 0 :(得分:1)

您可以像使用线宽一样在distplot中提供kde_kws = {'linestyle':'-'}中的线型arg-在'-'和'-'之间切换线型以实现所需的效果。 / p>

示例

import numpy as np; np.random.seed(10)
import seaborn as sns; sns.set(color_codes=True)
mean, cov = [0, 2], [(1, .5), (.5, 1)]
x, y = np.random.multivariate_normal(mean, cov, size=50).T
ax = sns.distplot(x, hist = False, kde=True, kde_kws={'linestyle': '--'})

答案 1 :(得分:1)

正确的方法是使用循环仪:

# added this:
from itertools import cycle
ls = ['-','--',':','-.','-','--',':','-.','-','--',':','-.','-','--',':','-.','-','--',':','-.','-','--',':','-.']
linecycler = cycle(ls)

products = list(data_cleaned.columns)
print('products: \n',products)
for i, product in enumerate(products):
    subset = data_cleaned[data_cleaned[product]>0][product]
    ax = sns.distplot(subset,hist=False,kde=True,kde_kws={'linewidth':3,'linestyle':next(linecycler)},label=product)
# loop through next(linecycler)

sns.set(rc = {'figure.figsize':(25,10)})
#sns.palplot()
palette_to_use = sns.color_palette("hls", 21)
sns.set_palette(palette_to_use)
#cmap = ListedColormap(sns.color_palette().as_hex())
plt.legend(prop={'size': 16}, title = 'Product')
plt.title('Density Plot with Multiple Products')
plt.xlabel('log10 of monthly spend')
plt.ylabel('Density')

Now the lines are more easily discerned