ScalaBoy
ScalaBoy

Reputation: 3392

How to add labels to a plot?

I wonder if it's possible to add labels to the peaks of Y axis values in time series plot.

enter image description here

In particular, I want to add the label with Date to the peaks when Y value is greater than 1200.

This is how I created a plot:

df[["DATE","DEPARTURE_DELAY_MIN"]].set_index('DATE').plot(figsize=(20,10))
_ = plt.xlabel("Date")
_ = plt.ylabel("Daily delay (minutes)")

Upvotes: 0

Views: 345

Answers (1)

John Karasinski
John Karasinski

Reputation: 1006

Here's a short working example to get you started:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Generate repeatable results
np.random.seed(0)

# Generate a bunch of noisy looking data and shuffle it
data = np.append(np.random.normal(200, 100, 990), np.random.normal(1200, 300, 10))
np.random.shuffle(data)

# Make the dataframe
df = pd.DataFrame({'Date': np.arange(1000), 'data_values': data})
df['over_value'] = df['data_values'] > 1200

# Create a plot
f, ax = plt.subplots()
df.plot(x='Date', y='data_values', ax=ax, legend=None)

# Iterate through the relevant rows and annotate
for _, row in df.query('over_value').iterrows():
    ax.annotate(int(row['data_values']), 
                xy=(row['Date'], row['data_values']))

plt.show()

enter image description here

Upvotes: 1

Related Questions