Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

python - Multi-line chart with seaborn tsplot

I want to create a smoothed line chart using matplotlib and seaborn.

This is my dataframe 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
...     ...          ...

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')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

Complete example:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...