【问题标题】:Second y-axis time series seaborn第二个 y 轴时间序列 seaborn
【发布时间】:2018-05-15 10:57:03
【问题描述】:

使用数据框

df = pd.DataFrame({
    "date" : ["2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04"],
    "column1" : [555,525,532,585],
    "column2" : [50,48,49,51]
})

可以使用seaborn 进行绘图,例如column1 使用sns.tsplot(data=df.column1, color="g")。

我们如何在 seaborn 中绘制两个 y 轴的时间序列?

【问题讨论】:

  • 我建议不要将tsplot 用于正常的时间序列。参见例如昨天的question。
  • 正如它所说,人们认为他们应该使用 tsplot 来使用 tsplot 绘制他们的时间相关数据,但它实际上从未为此目的而设计。
  • 另见 seaborn 的作者this comment。

标签: python seaborn


【解决方案1】:

由于seaborn 是建立在matplotlib 之上的,您可以使用它的强大功能:

import matplotlib.pyplot as plt
sns.lineplot(data=df.column1, color="g")
ax2 = plt.twinx()
sns.lineplot(data=df.column2, color="b", ax=ax2)

【讨论】:

  • 这似乎是一个解决方案,但传说不一致,因为第二个会出现在那里。
【解决方案2】:

我建议使用法线图。您可以通过ax.twinx() 获得双轴。

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"date": ["2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04"],
                   "column1": [555,525,532,585], 
                   "column2": [50,48,49,51]})

ax = df.plot(x="date", y="column1", legend=False)
ax2 = ax.twinx()
df.plot(x="date", y="column2", ax=ax2, legend=False, color="r")
ax.figure.legend()
plt.show()

【讨论】:

  • OP 确实指定了一个 seaborn 解决方案。
  • 是的,但是在 90% 的情况下,当有人想要“使用 seaborn”时,他们只是没有意识到 seaborn 只是一个不错但不完整的 matplotlib 接口,而且 pandas 包装东西的方式可能是同样合适。另请注意,在编写此答案时,seaborn 没有 lineplot 函数。
  • 很好的解决方案。使用pandas 的secondary_y 参数时,我无法绘制单个图例并将图例移到图之外。
【解决方案3】:

您可以根据@Andrey Sobolev 的解决方案尝试以下代码,但它也会生成完整的图例。

from matplotlib.lines import Line2D
    
g = sb.lineplot(data=df.column1, color="g")
sb.lineplot(data=df.column2, color="b", ax=g.axes.twinx())
g.legend(handles=[Line2D([], [], marker='_', color="g", label='column1'), Line2D([], [], marker='_', color="b", label='column2')])

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    相关资源
    最近更新 更多