Plot dates with Pandas and Seaborn

Marcelo Lazaroni

I have a DataFrame where each row is an event and it has a column of datetime values specifying the date and time of the event.

I just want to plot the amount of events for each day and be able to specify the start and end date of the x axis. How can I do that?

Nickil Maveli

Consider a DF containing a single column having datetime values as shown:

df = pd.DataFrame(pd.date_range('1/1/2016', periods=10, freq='D'), columns=['Date'])

enter image description here

Concatenate a sample of the original DF with itself to create duplicated values(say, 5)

df_dups = pd.concat([df, df.sample(n=5, random_state=42)], ignore_index=True)

Compute it's unique counts by stacking it into a series object.

plotting_df = df_dups.stack().value_counts().reset_index(name='counts')

Scatter Plot:

As only numerical values are supported for both x and y axis as args for the built-in scatter plot method, we must call the plot_date function of matplotlib axes object to retain the dates as it is.

fig, ax = plt.subplots()
ax.plot_date(plotting_df['index'], plotting_df['counts'], fmt='.', color='k')
ax.set_ylim(0, plotting_df['counts'].values.max()+1)
fig.autofmt_xdate()
plt.xlabel('Date')
plt.ylabel('Counts')
plt.show()

Image

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related