第二个y轴时间序列seaborn

2024-09-30 18:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

使用数据帧

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来作图,也可以用sns.tsplot(data=df.column1, color="g")来作图。

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


Tags: 数据dataframedfdatadate时间绘制seaborn
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()

enter image description here

由于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)

相关问题 更多 >