我想使用 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')
最佳答案
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()
还值得注意的是 tsplot is deprecated从 seaborn 版本 0.8 开始。因此,无论如何都可能值得使用其他方法来绘制数据。
关于python - 带有 seaborn tsplot 的多折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45327767/