2017-07-26 58 views
2

我想用matplotlib和seaborn创建一个平滑的折线图。带seaborn tsplot的多线图

这是我的数据帧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',熊猫绘图方法就足够了。 – mwaskom

回答

6

tsplot有点奇怪或至少strangly记录。如果提供了一个数据帧,它假定必须存在一个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。因此可能有必要使用其他方式来绘制数据。

1

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

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