Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
Control scale spacing
So far, we’ve let Matplotlib handle the scale position on the coordinate axis automatically, but sometimes we need to override the default coordinate axis scale configuration to more quickly estimate the coordinates of points in the graph.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = 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()
Copy the code
The above code forces the horizontal scale to be rendered every 5 unit steps. In addition, we have added sub-scales, which are spaced at 1 unit step, and the steps are described as follows:
- First instantiate a Axes object — used to manage the Axes in the graph:
ax=plot.Axes()
. - Then use the
Locator
Example Set the primary and secondary scales for the xaxis (Ax.xaxis) or yaxis (ax.yaxis).
Also add auxiliary mesh for sub-scale:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = 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()
Copy the code
Tips: We already know that you can use plt.grid() to add secondary grids, but this function also has an optional parameter which, which has three optional values: "minor", "major", and "both" for displaying only minor scales, only major scales, and both scales respectively.
Control scale label
It is time to introduce the setting of scale labels. Scale labels are coordinates in the graphics space. Although digital scale labels are sufficient for most scenarios, they are not always sufficient. For example, if we want to display the revenue of 100 companies, we need to label the abscissa scale with the company name, not the number; Also for time series, we want the abscissa scale labeled with date… . With this requirement in mind, we need to use the API that Matplotlib provides for this to control the calibration labels. You can set calibration labels for any Matplotlib graph by following these steps:
import numpy as np
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
name_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 = 'c', align = 'center')
plt.show()
Copy the code
Tips: We first use the Ticker. Locator instance to generate the location of the scale, and then use the Ticker. Formatter instance to generate labels for the scale. The FixedFormatter gets the labels from the list of strings and sets the axes with the Formatter instance. We also used FixedLocator to ensure that the center of each label is aligned exactly in the middle of the scale.
Easier setup
Although you can control the scale labels using the above method, you can see that this method is too complicated. If the scale labels are a fixed list of characters, you can use the following simple setting method:
import numpy as np
import matplotlib.pyplot as plt
name_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 = 'c', align = 'center')
plt.xticks(pos_list, name_list)
plt.show()
Copy the code
Tips: Using the plt.xticks() function to provide a fixed label for a fixed set of ticks, which takes a list of locations and a list of names as parameter values, shows that this approach is simpler to implement than the first approach.
Advanced scale label control
Not only can fixed tags be used, but function-generated tags can be used using the Ticker API:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def make_label(value, pos) :
return '% 0.1 f % %' % (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= 'c', ls = The '-')
plt.show()
Copy the code
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 a coordinate label, which is more flexible than giving a fixed list of strings. To use custom functions, you need to use a FuncFormatter instance -- a formatted instance that takes a function as an argument.
This way of delegating the actual task of generating labels to other functions is called the Delegation pattern, and it’s a beautiful programming technique. For example, we want to display each scale as a date, which can be done using the standard Python time and date functions:
import numpy as np
import datetime
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
start_date = datetime.datetime(1998.1.1)
def make_label(value, pos) :
time = start_date + datetime.timedelta(days = 365 * 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= 'c', ls = The '-')
labels = ax.get_xticklabels()
plt.setp(labels, rotation = 30.)
plt.show()
Copy the code
Tips: You can use Ax.get_xtickLabels () to get graduated label instances and then rotate the labels to avoid overlap between long labels using the plt.setp() function, which takes the graduated label instances and the rotation Angle as parameter values.
Series of links
Matplotlib common statistical graph drawing
Matplotlib uses custom colors to draw statistics
Matplotlib controls line style and line width
Matplotlib custom style to draw beautiful statistics
Matplotlib adds text instructions to the graph
Matplotlib adds comments to the graph
Matplotlib adds auxiliary grids and auxiliary lines to the graph
Matplotlib adds custom shapes