Python 3.x 如何在seaborn regplot中自动替换或循环线型?

Python 3.x 如何在seaborn regplot中自动替换或循环线型?,python-3.x,matplotlib,seaborn,Python 3.x,Matplotlib,Seaborn,我希望同一图表上的21行数据能够更容易用图例解释。例如,也许我可以让其他每一个图例条目/行都用破折号而不是一条连续的线来显示。我对Seaborn和Matplotlib的混合使用让我感到困惑——我不知道如何以交替的方式在其中添加破折号 products=列表(数据列) 打印('产品:\n',产品) 对于i,枚举中的产品(产品): 子集=数据已清理[数据已清理[产品]>0][产品] distplot(子集,hist=False,kde=True,kde_-kws={'linewidth':3},la

我希望同一图表上的21行数据能够更容易用图例解释。例如,也许我可以让其他每一个图例条目/行都用破折号而不是一条连续的线来显示。我对Seaborn和Matplotlib的混合使用让我感到困惑——我不知道如何以交替的方式在其中添加破折号

products=列表(数据列)
打印('产品:\n',产品)
对于i,枚举中的产品(产品):
子集=数据已清理[数据已清理[产品]>0][产品]
distplot(子集,hist=False,kde=True,kde_-kws={'linewidth':3},label=product)
如果i%2==0:
plt.plot(子集“-”,破折号=[8,4,2,4,2,4])
sns.set(rc={'figure.figsize':(25,10)})
#sns.palplot()
调色板使用=sns.调色板(“hls”,21)
sns.set_调色板(调色板要使用)
#cmap=ListedColormap(sns.color\u palete().as\u hex())
plt.legend(prop={'size':16},title='Product')
产品名称(“多产品密度图”)
plt.xlabel(“每月支出的log10”)
plt.ylabel('密度')
这是我当前的输出:

您可以在distplot中的kde_kws={'linestyle':'--}中提供线型参数,就像您在线宽中所做的那样-在'-'和'--'之间交替使用线型以达到所需的效果

范例

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': '--'})

正确的方法是使用自行车:

# 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')

这只显示了如何修改其中一条线-它不会循环使用线型-因此,它强制我显式地创建每个轴。我的要求是可以绘制不同数量的轴。我对这一要求感到困惑,因为您的示例显示了一个轴,我的假设是您可以提前绘制,并通过sns.distplot(ax=some_ax)将每条线绘制到它上。您可能希望更改问题的名称,以更好地反映您在各种线型之间循环的要求,而不是在实线和虚线之间交替。您的解决方案如何进行任何交替?哦,我假设混淆是将kwarg传递给seaborn以获得线型(对于某些seaborn plot元素,这有时是不可能的),而不是循环的细节-使用该循环对象是一个很好的方法!有关更多参考: