Seaborn tsplot的多线图

3

我希望使用matplotlib和seaborn创建平滑的折线图。

这是我的数据框df

hour    direction    hourly_avg_count
0       1            20
1       1            22
2       1            21
3       1            21
..      ...          ...
24      1            15
0       2            24
1       2            28
...     ...          ...

折线图应该包含两条线,一条用于 direction 等于 1,另一条用于 direction 等于 2。X 轴是 hour,Y 轴是 hourly_avg_count。 我尝试过这个,但是我看不到这些线。
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt

plt.figure(figsize=(12,8))
sns.tsplot(df, time='hour', condition='direction', value='hourly_avg_count')

1
这里没有必要使用 tsplot,pandas 绘图方法就足够了。 - mwaskom
2个回答

13

tsplot函数有些奇怪或者至少文档描述的比较奇怪。如果你给它提供了一个数据框,它会假设必须有一个名为unit和一个名为time的列,因为它会在这两个列上进行内部轴心旋转。如果要使用tsplot绘制多个时间序列,则还需要向unit参数提供参数;可以将其设置为与condition相同。

sns.tsplot(df, time='hour', unit = "direction", 
               condition='direction', value='hourly_avg_count')

完整示例:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

hour, direction = np.meshgrid(np.arange(24), np.arange(1,3))
df = pd.DataFrame({"hour": hour.flatten(), "direction": direction.flatten()})
df["hourly_avg_count"] = np.random.randint(14,30, size=len(df))

plt.figure(figsize=(12,8))
sns.tsplot(df, time='hour', unit = "direction", 
               condition='direction', value='hourly_avg_count')

plt.show()

在此输入图像描述

值得注意的是,从seaborn 0.8版本开始,tsplot已被弃用。因此,可能值得使用其他方法来绘制数据。


2
尝试添加一个虚拟单位列。第一部分是创建一些合成数据,请忽略。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

df1 = pd.DataFrame({
"hour":range(24),
"direction":1,
"hourly_avg_count": np.random.randint(25,28,size=24)})

df2 = pd.DataFrame({
"hour":range(24),
"direction":2,
"hourly_avg_count": np.random.randint(25,28,size=24)})

df = pd.concat([df1,df2],axis=0)
df['unit'] = 'subject'

plt.figure()
sns.tsplot(data=df, time='hour', condition='direction',
unit='unit', value='hourly_avg_count')

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接