When drawing large and complex plots in Matplotlib, we need a way of labelling certain portion or points of interest on the graph.
Text and Annotation
• When
drawing large and complex plots in Matplotlib, we need a way of labelling
certain portion or points of interest on the graph. To do so, Matplotlib
provides us with the "Annotation" feature which allows us to plot
arrows and text labels on the graphs to give them more meaning.
• There
are four important parameters that you must always use with annotate().
a) text: This defines the text label.
Takes a string as a value.
b) xy: The place where you want
your arrowhead to point to. In other words, the place you want to annotate.
This is a tuple containing two values, x and y.
c) xytext: The coordinates for where
you want to text to display.
d) arrowprops: A
dictionary of key-value pairs which define various properties for the arrow,
such as color, size and arrowhead type.
Example :
importmatplotlib.pyplot
as plt
importnumpy
as np
fig, ax
= plt.subplots()
x =
np.arange(0.0, 5.0, 0.01)
y
=np.sin(2* np.pi *x)
#
Annotation
ax.annotate('Local
Max',
xy = (3.3, 1),
xytext (3, 1.8),
arrowprops = dict(facecolor = 'green',
shrink =0.05))
ax.set_ylim(-2,
2)
plt.plot(x,
y)
plt.show()
Output:
Example :
importplotly.graph_objectsasgo
fig=go.Figure()
fig.add_trace(go.Scatter(
x=[0,1,2,3,4,5,6,7,8],
y=[0,1,3,2,4,3,4,6,5]
))
fig.add_trace(go.Scatter(
x=[0,1,2,3,4,5,6,7,8],
y=[0,4,5,1,2,2,3,4,2]
))
fig.add_annotation(x=2,y=5,
text="Text
annotation with arrow",
showarrow=True,
arrowhead=1)
fig.add_annotation(x=4,y=4,
text="Text
annotation without arrow",
showarrow=False,
yshift =
10)
fig.update_layout(showlegend=False)
fig.show()
Output:
Foundation of Data Science: Unit V: Data Visualization : Tag: : Matplotlib | Data Visualization - Text and Annotation
Foundation of Data Science
CS3352 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation