Show Sidebar Hide Sidebar

Text and Annotations in matplotlib

How to add text labels and annotations to plots in matplotlib.

import matplotlib.pyplot as plt
import numpy as np

import plotly.plotly as py
import plotly.tools as tls
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(2.9, 1.1),
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.ylim(-2,2)
fig = plt.gcf()
plot_url = py.plot_mpl(fig, filename='mpl-simple-annotation')
Inspired by Matplotlib Docs
import matplotlib.pyplot as plt
import numpy as np

import plotly.plotly as py
import plotly.tools as tls
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api


t = np.arange(-5.0, 5.0, 0.01)
s = np.sin(4 * np.pi * t) * np.exp(-5 * np.absolute(t))

mpl_fig = plt.figure()
ax = mpl_fig.add_subplot(111)

line, = ax.plot(t, s, lw=2)
plt.annotate('Global Maximum', xy=(0.08, 0.58), xytext=(0.08, 0.58),
             arrowprops=dict(facecolor='black', shrink=0.05))

ax.set_ylim(-2,2)
ax.set_xlim(-5,5)


plotly_fig = tls.mpl_to_plotly( mpl_fig )
# Annotations are hidden by default..
plotly_fig['layout']["annotations"][0].update({
                                               "showarrow":True
                                             })

plot_url = py.plot_mpl(plotly_fig, filename='mpl-annotation-with-arrow')
Inspired by Matplotlib Docs
import matplotlib.pyplot as plt
import numpy as np

import plotly.plotly as py
import plotly.tools as tls
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api


t = np.arange(-5.0, 5.0, 0.01)
s = np.sin(4 * np.pi * np.absolute(t)) * np.exp(-5 * np.absolute(t))

mpl_fig = plt.figure()
ax = mpl_fig.add_subplot(111)

line, = ax.plot(t, s, lw=2)

plt.annotate('Peak 1', xy=(-0.08, 0.58), xytext=(-0.08, 0.58),
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.annotate('Peak 2', xy=(0.08, 0.58), xytext=(0.08, 0.58),
             arrowprops=dict(facecolor='black', shrink=0.05))


ax.set_ylim(-2,2)
ax.set_xlim(-5,5)

plotly_fig = tls.mpl_to_plotly( mpl_fig )

plotly_fig['layout']["annotations"][0].update({"showarrow":True})
plotly_fig['layout']["annotations"][1].update({"showarrow":True,"ax":35,"ay":-30})
plotly_fig['layout']["annotations"][1]["font"].update({"size":16})


plot_url = py.plot_mpl(plotly_fig, filename='mpl-annotation-with-custom-font-size')
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.