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 control the axis scale spacing and label by Matplotlib

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how Matplotlib controls the scale spacing and labels of axes. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Control scale spacing

So far, we have asked Matplotlib to automatically handle the position of the scale on the axis, but sometimes we need to override the default axis scale configuration to estimate the coordinates of the point in the graph more quickly.

Import numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerx = np.linspace (- 20,20,1024) y = np.sinc (x) ax = plt.axes () ax.xaxis.set_major_locator (ticker.MultipleLocator (5)) ax.xaxis.set_minor_locator (ticker.MultipleLocator (1)) plt.plot (x, y, c ='m') plt.show ()

The above code forces the horizontal scale to be rendered every 5 unit steps. In addition, we have added a sub-scale with an interval of 1 unit step. The steps are as follows:

First instantiate an Axes object-- used to manage the axes in the drawing: ax=plot.Axes ().

Then use the Locator instance to set the primary and secondary scales for the x-axis (ax.xaxis) or y-axis (ax.yaxis).

Also add a secondary grid for the subscale:

Import numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerx = np.linspace (- 20,20,1024) y = np.sinc (x) ax = plt.axes () ax.xaxis.set_major_locator (ticker.MultipleLocator (5)) ax.xaxis.set_minor_locator (ticker.MultipleLocator (1)) plt.grid (True, which='both', ls='dashed') plt.plot (x, y, c ='m') plt.show ()

Tips: we already know that you can use plt.grid () to add an auxiliary grid, but this function also has an optional parameter, which, which has three optional values: "minor", "major", and "both", which are used to display only the secondary scale, only the primary scale, and the primary and secondary scale at the same time.

Control scale label

It's time to introduce the setting of the scale label, which is the coordinate in the graphics space. Although the digital scale label is sufficient for most scenarios, it does not always meet the requirements. For example, if we need to show the revenue of 100 companies, we need the Abscissa scale label as the company name, not the number; similarly, for the time series, we want the Abscissa scale label to be date. Given such requirements, we need to use the API control scale tag provided by Matplotlib for this purpose.

You can set a scale label for any Matplotlib drawing by following these steps:

Import numpy as npimport matplotlib.ticker as tickerimport matplotlib.pyplot as pltname_list = ('Apple',' Orange', 'Banana',' Pear', 'Mango') value_list = np.random.randint (0,99 Size = len (name_list) pos_list = np.arange (len (name_list)) ax = plt.axes () ax.xaxis.set_major_locator (ticker.FixedLocator ((pos_list) ax.xaxis.set_major_formatter (ticker.FixedFormatter ((name_list)) plt.bar (pos_list, value_list, color = 'cations, align =' center') plt.show ()

Tips: we first use the ticker.Locator instance to generate the location of the tick, and then use the ticker.Formatter instance to generate a label for the tick. FixedFormatter takes the label from the list of strings and sets the axis with the Formatter instance. At the same time, we also use FixedLocator to ensure that the center of each label is exactly aligned with the middle of the scale.

Easier way to set up

Although you can control the scale label using the above method, you can see that this method is too complex, and if the scale label is a fixed list of characters, you can use the following simple setting methods:

Import numpy as npimport matplotlib.pyplot as pltname_list = ('Apple',' Orange', 'Banana',' Pear', 'Mango') value_list = np.random.randint (0,99, size = len (name_list)) pos_list = np.arange (len (name_list)) plt.bar (pos_list, value_list, color =' centering, align = 'center') plt.xticks (pos_list, name_list) plt.show ()

Tips: use the plt.xticks () function to provide a fixed label for a fixed set of scales, which accepts a list of locations and names as parameter values, which shows that this method is easier to implement than the first method.

Advanced scale label control

Not only can you use fixed tags, but with ticker API you can use tags generated by functions:

Import numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerdef make_label (value, pos): return'% 0.1f%%'% (100. * value) ax = plt.axes () ax.xaxis.set_major_formatter (ticker.FuncFormatter (make_label)) x = np.linspace (0,1,256) plt.plot (x, np.exp (- 10 * x), c ='c') plt.plot (x, np.exp (- 5 * x), c = 'croup, ls =' -') plt.show ()

In this example, the scale label is generated by the custom function make_label. This function takes the coordinates of the scale as input and returns a string as the coordinate label, which is more flexible than giving a fixed list of strings. To use a custom function, you need to use an instance of FuncFormatter-- a formatted instance that takes a function as an argument.

This method of assigning the actual task of generating tags to other functions is called delegation mode, which is a beautiful programming technique. For example, we want to display each tick as a date, which can be done using the standard Python time and date functions:

Import numpy as npimport datetimeimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerstart_date = datetime.datetime (0,1,1) def make_label (value, pos): time = start_date + datetime.timedelta (days = 1998 * value) return time.strftime ('% b% y') ax = plt.axes () ax.xaxis.set_major_formatter (ticker.FuncFormatter (make_label)) x = np.linspace (0,1,256) plt.plot (x, np.exp (- 10 * x) C ='c') plt.plot (x, np.exp (- 5 * x), c = 'croup, ls =' -') labels = ax.get_xticklabels () plt.setp (labels, rotation = 30.) plt.show ()

Tips: you can use ax.get_xticklabels () to get the scale label instance, and then rotate the label to avoid overlap between long tags. Rotation uses the plt.setp () function, which accepts the scale label instance and rotation angle as parameter values.

This is the end of this article on "how Matplotlib controls axis scale spacing and labels". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

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: 0

*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