具有seaborn tsplot的多线图 [英] Multi-line chart with seaborn tsplot
问题描述
我想使用matplotlib和seaborn创建平滑的折线图.
I want to create a smoothed line chart using matplotlib and 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
.
The line chart should contain two lines, one for direction
equal to 1, another for direction
equal to 2. The X axis is hour
and Y axis is hourly_avg_count
.
我尝试过,但是看不到线条.
I tried this, but I cannot see the lines.
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')
推荐答案
tsplot
有点奇怪,或者至少被严格记录在案.如果提供了一个数据框,则它假定必须存在unit
和time
列,因为它在内部围绕这两个旋转.因此,要使用tsplot
绘制多个时间序列,您还需要向unit
提供一个参数.这可以与condition
相同.
The tsplot
is a bit strange or at least strangly documented. If a dataframe is supplied to it, it assumes that there must be a unit
and a time
column present, as it internally pivots about those two. To use tsplot
to plot several time series you would therefore need to supply an argument to unit
as well; this can be the same as 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()
还值得注意的是, tsplot已弃用为版本0.8的版本.因此,可能仍然值得使用其他方式来绘制数据.
Also worth noting that tsplot is deprecated as of seaborn version 0.8. It might thus be worth to use some other way to plot the data anyways.
这篇关于具有seaborn tsplot的多线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!