带seaborn tsp的多线图

2024-06-12 14:47:23 发布

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

我想用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')

Tags: 数据importdfmatplotlibascountpltseaborn
2条回答

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()

enter image description here

同样值得注意的是tsplot is deprecated从seaborn版本0.8开始。因此,使用其他方法绘制数据可能是值得的。

尝试添加虚拟单元列。第一部分是创建一些合成数据,请忽略。

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

相关问题 更多 >