Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add text tags and comments to images by Python+Matplotlib

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "Python+Matplotlib how to add text tags and comments to the image", the text explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Python+Matplotlib how to add text tags and comments to the image" it!

1. Add a text label plt.text ()

Used to add text to the specified coordinates on the image during the drawing process. What you need to use is the plt.text () method.  

There are three main parameters:

Plt.text (x, y, s)

Where x _ ray y represents the x and y axis coordinates of the transfer point. S represents a string.

It should be noted that the coordinates here, if set with xticks or yticks tags, refer not to the label, but to the original values of x and axis when drawing.

Because there are too many parameters, no longer explain them one by one, learn their usage according to the code.

Ha='center' indicates that the vertical alignment is centered, and fontsize=30 indicates that the font size is 30, which means that the rotation angle is-25 degrees. C sets the color, and alpha sets the transparency.

Va indicates horizontal alignment.

The following code adds two paragraphs of text to the image, one is the italic watermark of "the stock market is risky, investment should be careful", the transparency is 0.4.

The other is to mark the closing price of the day near each break point of the break line.

Import matplotlib.pyplot as pltplt.rcParams ['font.sans-serif'] = [' SimHei'] plt.rcParams ['axes.unicode_minus'] = Falsex = range (9) y = [5.12,5.15,5.13,5.10,5.2,5.25,5.19,5.24 5.31] c = 0.5 * (min (x) + max (x)) d = min (y) + 0.3 * (max (y)-min (y)) # watermark effect plt.text (c, d, 'stock market risk Be cautious when entering the market:', ha='center', fontsize=30, rotation=-25, caterpillar gradation, alpha=0.4) plt.plot (A closing price of x, y, label=' stock A, caterpillar, ls='-.', marker='D', lw=2) plt.xticks (x, ['2022-03-27,' 2022-03-28, '2022-03-29,' 2022-03-30, '2022-03-31, 2022-04-01' '2022-04-04,' 2022-04-05, '2022-04-06], rotation=45) plt.title (' closing sequence chart of a stock') plt.xlabel ('date') plt.ylabel ('price') plt.grid (True) plt.legend () # Mark the daily closing price for a, b in zip (x, y): plt.text (a, bau0.01,'% .1f'% b, ha='center') Va='bottom', fontsize=9) plt.show ()

two。 Add comment plt.annotate ()

Add comments based on the code in the previous example. An annotation is an explanation of a location in an image, which can be pointed with an arrow.

The plt.annotate () method is used to add comments

The common parameters in its syntax are as follows

Plt.annotate (str,xy,xytext,xycoords,arrowcoords)

Where str is the string to be used by the comment, that is, the comment text

Xy refers to the coordinate point being annotated.

Xytext refers to the location where the comment text is to be written

Xycoords is the coordinate system attribute of the annotated point, that is, how the coordinates of the point are described. The setting value defaults to "data", which is described by (xPowery) coordinates. Other optional settings are as follows, where figure refers to the entire canvas as a frame of reference. Axes means only for one of the axes object regions.

The setting value describes the default value of data, indicating that the coordinate figure points of the annotated point takes the lower left corner of the drawing area as the coordinate origin, the unit is the number of points figure pixels takes the lower left corner of the drawing area as the coordinate origin, the unit is the number of pixels figure fraction takes the lower left corner of the drawing area as the coordinate origin, the unit is the percentage axes points takes the lower left corner of the drawing area as the coordinate origin, and the unit is the number of points axes pixels takes the lower left corner of the drawing area as the coordinate origin. The unit is the number of pixels axes fraction takes the lower left corner of the drawing area as the coordinate origin, the unit is the percentage polar does not use the local data coordinate system, but uses polar coordinates to describe

Arrowprops is a dictionary that sets the properties of arrowheads. The parameters written outside this dictionary represent the properties of the comment text.

The values that can be set in the dictionary are

The setting value describes the width of the width arrow (not the head) the width of the head of the headwidth arrow the length of the head of the headlength arrow the color of the facecolor arrow the percentage of contraction at both ends of the shrink arrow (to the total length)? Keywords in any matplotlib.patches.FancyArrowPacth

Further explanation on these parameters: the total length of the arrow is first determined by the location coordinates of the annotated point and the position coordinates of the note text, and the length of the arrow can be further adjusted by adjusting the shrink key in the parameter arrowprops. Shrink represents the percentage of the total length (the length determined by the location coordinates of the annotated point and the position coordinates of the note text). When shrink is not set, shrink defaults to 0, that is, it is not shortened. When the shrink is very large, close to 1, the effect is equivalent to no shortening.

Take, for example, the point that marks the lowest price in the diagram. Add a red arrow at the target location and the words "lowest price".

Other more parameters, such as those about setting the font for comment text, c or color represents the color, and fontsize represents the font size. Try to learn more about your own properties.

Import matplotlib.pyplot as pltplt.rcParams ['font.sans-serif'] = [' SimHei'] plt.rcParams ['axes.unicode_minus'] = Falsex = range (9) y = [5.12,5.15,5.13,5.10,5.2,5.25,5.19,5.24 5.31] c = 0.5 * (min (x) + max (x)) d = min (y) + 0.3 * (max (y)-min (y)) # imitating watermark effect plt.text (c, d, 'stock market risk Be cautious when entering the market:', ha='center', fontsize=30, rotation=-25, caterpillar gradients, alpha=0.4) plt.plot (A closing price of x, y, label=' shares', caterpillar stocks, ls='-.', marker='D', lw=2) # plt.plot ([5.09,5.13,5.16,5.12,5.09,5.25,5.16,5.20,5.25], label=' shares B closing price', clockwise, ls=':', marker='H' Lw=4) plt.xticks (x, ['2022-03-27,' 2022-03-28, '2022-03-29,' 2022-03-30, '2022-03-31,' 2022-04-01, '2022-04-04, 2022-04-05,' 2022-04-06'] Rotation=45) plt.title ('closing sequence chart of a stock') plt.xlabel ('date') plt.ylabel ('price') plt.grid (True) plt.legend () # Mark the daily closing price for a, b in zip (x, y): plt.text (a, bread0.01,'% .1f'% b, ha='center', va='bottom', fontsize=9) # add note plt.annotate ('lowest price') (X [y.index (min (y))], min (y)), (x [y.index (min (y))] + 0.5, min (y)), xycoords='data', arrowprops=dict (facecolor='r', shrink=0.1), plt.show ()

The following is a different effect, the prompt "the stock market is risky, you need to be careful to enter the market" font to 50, opaque. The width of the added comment arrow is 3, the head width of the arrow is 10, the length is 20, shortened by 0.05, and the arrow is green, and the comment font is red. The code example is as follows:

Import matplotlib.pyplot as pltplt.rcParams ['font.sans-serif'] = [' SimHei'] plt.rcParams ['axes.unicode_minus'] = Falsex = range (9) y = [5.12,5.15,5.13,5.10,5.2,5.25,5.19,5.24,5.31] c = 0.5 * (min (x) + max (x)) d = min (y) + 0.3 * (max (y)-min (y)) plt.plot (x, y) Label=' shares A closing price, closing price, ls='-.', marker='D', lw=2) plt.xticks (x, ['2022-03-27,' 2022-03-28, '2022-03-29,' 2022-03-30, '2022-03-31,' 2022-04-01, '2022-04-04, 2022-04-05, 2022-04-06] Rotation=45) plt.title ('closing sequence chart of a stock') plt.xlabel ('date') plt.ylabel ('price') plt.grid (True) plt.legend () # Mark the daily closing price for a, b in zip (x, y): plt.text (a, bread0.01,'% .1f'% b, ha='center', va='bottom', fontsize=9) plt.text (c, d, 'stock market risk Be careful when entering the market:', ha='center', fontsize=50, rotation=-25, caterpillar r') plt.annotate ('lowest price', (x [y.index (min (y))], min (y)), (x [y.index (min (y))] + 2, min (y)), xycoords='data', arrowprops=dict (width=3,headwidth=10,headlength=20, facecolor='g',shrink=0.05), cymbals min ()

Thank you for your reading, the above is the content of "Python+Matplotlib how to add text tags and comments to the image", after the study of this article, I believe you have a deeper understanding of how to achieve Python+Matplotlib to add text tags and comments to the image, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 226

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report