Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text next to vertical line in matplotlib

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?

like image 323
user1700890 Avatar asked Dec 14 '16 22:12

user1700890


People also ask

How do I add text in matplotlib?

annotate() is used to add an annotation, with an optional arrow, at an arbitrary location of the Axes. Its xy parameter contains the coordinates for arrow and xytext parameter specifies the location of the text. Arrowprops parameter is used to style the arrow.

How do I fill a vertical line in matplotlib?

With the use of the fill_between() function in the Matplotlib library in Python, we can easily fill the color between any multiple lines or any two horizontal curves on a 2D plane.


1 Answers

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.

like image 155
J. P. Petersen Avatar answered Oct 29 '22 16:10

J. P. Petersen