0

I have a pandas dataframe consisting of 2 columns: Date and Event

I need to plot events along a timeline using the dates, but don't know how to do this in python. Can someone guide me on this?

My dataframe looks something like this:

Date | Event

2015-08-17 11:05:00 | Birthday

2017-04-10 09:10:02 | First Steps

3
  • Did you try googling what libraries are available for this kind of thing? Commented Jul 15, 2021 at 0:59
  • I've tried using Matplotlib, but with no success Commented Jul 15, 2021 at 1:02
  • You should show what you tried and ask a specific question about a problem you encountered. Commented Jul 15, 2021 at 21:48

1 Answer 1

3

Check this out: https://matplotlib.org/stable/gallery/lines_bars_and_markers/timeline.html

Basically, something like this:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
from datetime import datetime

df = pd.DataFrame(
    {
        'event': ['birthday', 'first steps'] * 5,
        'date': pd.date_range(start='1/1/2018', periods=10)        
    }
)

df['date'] = pd.to_datetime(df['date'])

levels = np.tile(
    [-5, 5, -3, 3, -1, 1],
    int(np.ceil(len(df)/6))
)[:len(df)]

fig, ax = plt.subplots(figsize=(12.8, 4), constrained_layout=True);
ax.set(title="A series of events")

ax.vlines(df['date'], 0, levels, color="tab:red");  # The vertical stems.
ax.plot(   # Baseline and markers on it.
    df['date'],
    np.zeros_like(df['date']),
    "-o",
    color="k",
    markerfacecolor="w"
);

# annotate lines
for d, l, r in zip(df['date'], levels, df['event']):
    ax.annotate(
        r,
        xy=(d, l),
        xytext=(-3, np.sign(l)*3),
        textcoords="offset points",
        horizontalalignment="right",
        verticalalignment="bottom" if l > 0 else "top"
    );

# format xaxis with 4 month intervals
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=4));
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"));
plt.setp(ax.get_xticklabels(), rotation=30, ha="right");

# remove y axis and spines
ax.yaxis.set_visible(False);
ax.yaxis.set_visible(False);
ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)    
ax.margins(y=0.1);
plt.show();

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

How are you stripping the time from the date-time? And currently my time is a Timestamp object, which is causing errors. How would you fix this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.