Add text next to vertical line
Asked Answered
S

1

15

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?

Sophisticated answered 14/12, 2016 at 22:27 Comment(0)
T
25

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.

Taxexempt answered 15/12, 2016 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.