【问题标题】:How can you add a trendline to a seaborn's lineplot?如何在 seaborn 的线图中添加趋势线?
【发布时间】:2020-03-07 21:14:16
【问题描述】:

这是我试图在 Seaborn 中重新创建的内容(这是使用 Matplotlib 完成的)

我在 Seaborn 中看到您可以使用 regplot(),但这个是用于散点图的。无论如何,如果我尝试使用它,它不会起作用,因为xdatetime,所以我做了一个Seaborn和Matplotlib的混合,它可以工作,但我不喜欢它,我认为必须有更好的方法,仅限 Seaborn。

x = range(0, len(hom.fecha))

plt.figure(figsize=(12, 9))
plt.style.use('fivethirtyeight')

chart = sns.lineplot(x='fecha', y='n', data=df, 
                     hue='sexo', markers=True)
chart.set(title='Personas Migrantes', ylabel='# Personas', xlabel="Fecha")

# Linear regressions for each sex
z = np.polyfit(x, hom.n, 1)
p = np.poly1d(z)
plt.plot(hom.fecha, p(x), c="b", ls=":")

z = np.polyfit(x, muj.n, 1)
p = np.poly1d(z)
plt.plot(hom.fecha, p(x), c="r", ls=':')

我得到了这张照片:

我认为这比第一个更令人愉快,但我只是不明白如何仅使用 seaborn 添加趋势线。

有什么想法吗?

=== 编辑 ===

如果我使用regplot(),它会抛出异常...

sns.regplot(x="fecha", y="n", data=df)

这个...(它绘制了一些东西,比如散点图,带有点)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-70-0f60957abc3f> in <module>
----> 1 sns.regplot(x="fecha", y="n", data=df)

blah blah blah

TypeError: unsupported operand type(s) for *: 'Timestamp' and 'float'

【问题讨论】:

  • 我不明白你的情节有什么问题。
  • 剧情还行,就是用seaborn和matplotlib写的,颜色有点偏。我想要sns.lineplot(x='fecha', y='n', data=df, hue='sexo', linearregression=True) ????
  • 这就是regplot 的用途(您不需要显示这些点)。由于 seaborn 仅使用 matplotlib,因此每个 seaborn 图都是一个 matplotlib 图。颜色由fivethirtyeight 样式确定(与seaborn 无关),您只需reset the color cycle 即可获得与前几行相同的颜色。
  • seaborn 不支持日期变量作为回归的输入,因此您必须以一种或另一种方式回退到 matplotlib。
  • 哦,好吧,错误告诉您不能将 regplot 与时间戳数据一起使用。您可以将时间戳转换为数字,绘制回归图,然后为轴创建一个代码和格式化程序。这将比从一开始就使用 matplotlib 做更多的工作。

标签: python matplotlib data-visualization seaborn


【解决方案1】:

我看到这是一岁了,但我刚刚遇到并解决了一个类似的问题,所以我将把解决方案留在这里。

您的 regplot 的问题是您使用列名作为 x 轴,但是(我假设)“fecha”实际上是索引的名称而不是列的名称。如果你要走这条线:

sns.regplot(x="fecha", y="n", data=df)

并将其更改为:

sns.regplot(x=df.index, y="n", data=df)

然后我希望它可以工作。您可能还想取出默认绘制的置信区间(添加参数 ci=False)并将颜色更改为红色或蓝色或其他。

我知道现在帮助你可能为时已晚,但我希望它可以帮助别人!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2013-02-12
    相关资源
    最近更新 更多