python - 带有 seaborn tsplot 的多折线图

标签 python matplotlib seaborn

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

enter image description here

还值得注意的是 tsplot is deprecated从 seaborn 版本 0.8 开始。因此,无论如何都可能值得使用其他方法来绘制数据。

关于python - 带有 seaborn tsplot 的多折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45327767/

相关文章:

python - 使用 matplotlib 绘制向日葵散点图

python - SSL : CERTIFICATE_VERIFY_FAILED error when loading data into seaborn?

python - 避免在 swarmplot 覆盖的 seaborn boxplot 中重复图例

python - 错误 : Invalid Syntax on "def"

python - Kivy:在桌面上隐藏鼠标光标

python - 如何在 matplotlib 中制作按密度着色的散点图?

python - 使用循环在seaborn直方图子图中添加分位数和平均线

python - 使用 pandas 函数根据 DataFrame 变量在 DataFrame 中创建新列

python - Pandas 数据帧 : How to extract the last two string type numbers from a column which doesn't always end with the two numbers

python - 模块未找到错误 : No module named 'matplotlib' even though the package is installed