Add text next to vertical line in matplotlib

user1700890 picture user1700890 · Dec 14, 2016 · Viewed 24.8k times · Source

Here is my code:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import numpy as np
fig, ax = plt.subplots(1,1)
sample_dates = np.array([datetime.datetime(2000,1,1), datetime.datetime(2001,1,1)])
sample_dates = mdates.date2num(sample_dates)
plt.vlines(x=sample_dates, ymin=0, ymax=10, color = 'r')
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y'))
plt.show()

It plots two red lines at certain dates on x-axis. Now I would like to add text to every line. Text should be parallel to the line. Where do I start?

Answer

J. P. Petersen picture J. P. Petersen · Dec 15, 2016

You can use Matplotlib text function to draw text on the plots. It has a lot of parameters that can be set. See documentation and examples here.

Here is an example with some text parallel to the lines:

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

fig, ax = plt.subplots(1,1)
sample_dates = np.array([datetime.datetime(2000,1,1), datetime.datetime(2001,1,1)])
sample_dates = mdates.date2num(sample_dates)
plt.vlines(x=sample_dates, ymin=0, ymax=10, color = 'r')
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y'))

for i, x in enumerate(sample_dates):
    text(x, 5, "entry %d" % i, rotation=90, verticalalignment='center')

plt.show()

Should look like this:

New plot result.