2017-07-26 197 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