Customization of chart auxiliary elements and beautification of icon styles

1. The description of commonly used auxiliary elements in charts is as follows:

Coordinate axes: Divided into single coordinate axes and double coordinate axes. Single coordinate axes can be divided into horizontal coordinate axes (also known as horizontal coordinate axes) according to different directions.

(called the x-axis) and the vertical coordinate axis (also called the y-axis).

Title: Descriptive text representing the chart.

Legend: Used to indicate how each group of graphics in the chart is identified.

Grid: A number of lines starting from the axis scale and running through the plot area, used as a guide for estimating the values shown in the graph.

standard.

Reference Line: A straight line that marks a particular value on a coordinate axis.

Reference area: An area marking a special range on the coordinate axis.

Annotation text: Represents some comments and explanations on the graphics.

Tables: Tables used to emphasize more difficult-to-understand data.

1.1 Set axis labels, scale ranges and scale labels

1.1.1 Set axis labels
1. Set the x-axis label using the xlabel() function in the pyplot module

The syntax format of the xlabel() function is as follows:

xlabel(xlabel, fontdict=None, labelpad=None, **kwargs)

The meaning of each parameter of this function is as follows:

xlabel: Text representing the x-axis label.

fontdict: A dictionary representing the control label text style.

labelpad: Indicates the distance between the label and the axis border (including ticks and tick labels).

In addition, the Axes object can also set the x-axis label using the set_xlabel() method.

2. To set the label of the y-axis, use the ylabel() function in the pyplot module

The syntax format of the ylabel() function is as follows:

ylabel(ylabel, fontdict=None, labelpad=None, **kwargs)

The ylabel parameter of this function represents the text of the y-axis label, and the remaining parameters have the same meaning as the parameters of the xlabel() function.

No further details will be given here. In addition, the Axes object can also set the y-axis label using the set_ _ylabel0 method.

1.1.2 Set scale range and scale label
1. Set the scale range

Use the xlim() and ylim() functions in the pyplot module to set or get the scale range of the x-axis and y-axis respectively.

The syntax format of the xlim() function is as follows:

xlim(left=None, right=None, emit=True, auto=False, *, xmin=Noner, xmax=None)

The meanings of the commonly used parameters of this function are as follows:

left: represents the number of left digits in the x-axis scale value range.

right: Indicates the number of right digits in the x-axis scale value range.

emit: Indicates whether to notify observers of limit changes. The default is True.

auto: Indicates whether to allow automatic scaling of the x-axis. The default is True.

xmin: represents the minimum value of the x-axis scale.

xmax: represents the maximum value of the x-axis scale.

In addition, the Axes object can use the set_xlim() and set_ylim() methods to set the scale range of the x-axis and y-axis respectively.

2. Set tick labels

Use the xticks() and yticks() functions of the pyplot module to set or get the tick mark positions and tick labels of the x-axis and y-axis respectively. The syntax format of the xticks() function is as follows:

xticks (ticks=None, labels=None, **kwargs)

The ticks parameter of this function represents the position list of tick display. It can also be set to an empty list to disable the x-axis tick;

labels represents a list of labels for the specified position scale.

In addition, the Axes object can use the set_xticks() or set_yticks() method to set the tick mark position of the x-axis or y-axis respectively, and use the set_xticklabels() or set_yticklabels() method to set the tick labels of the x-axis or y-axis respectively.

1.1.3 Add title and legend
1. Add title

Use the title() function in the pyplot module to add a chart title. The syntax format of the title() function is as follows:

title (label, fontdict-None, loc=’ center’ , pad=None, **kwargs)

The meanings of the commonly used parameters of this function are as follows:

label : Text representing the title.

fontdict: Represents a dictionary that controls the style of title text.

loc: Indicates the alignment style of the title, including three values: ‘left’, ‘right’ and ‘center’. The default value is ‘center’, which means the title is displayed in the center.

pad: represents the distance between the title and the top of the chart, the default is None.

Additionally, Axes objects can add a title to the chart using the set_title() method.

2. Add legend

Use the legend() function in the pyplot module to add a legend. The syntax format of the legend() function is as follows:

legend (handles, labels, loc, bbox_ to_anchor, ncol, title, shadow,

fancybox, *args, **kwargs )

The commonly used parameters of this function are introduced as follows:

(1) handles and labels parameters

The handles parameter represents a list composed of graphic identifiers, and the labels parameter represents a list composed of legend items. It should be noted that the handles and labels parameters should receive lists of the same length. If the received lists are of different lengths, the longer list will be truncated so that the length of the longer list and the shorter list are equal.

(2) loc parameter (used to roughly adjust the position of the legend in the entire drawing area)

The loc parameter is used to control the position of the legend in the chart. This parameter supports both string and numerical values. The description of each value and its corresponding legend position is shown in Table 1 below.

Table 1 Values of the loc parameter and their corresponding legend positions

(3) bbox_ to_anchor parameter (used to accurately adjust the position of the legend in the entire drawing area [x: 0-1, y: 0-1])

The bbox_to_anchor parameter is used to control the layout of the legend. This parameter receives a tuple containing two values. The first value is used to control the horizontal position of the legend display. The larger the value, the farther to the right the position of the legend display; the second value A numerical value is used to control the vertical position of the legend. The larger the value, the higher the position of the legend display.

(4) ncol parameter

The ncol parameter indicates the number of columns in the legend, and the default value is 1.

(5) title parameter

The title parameter represents the title of the legend, and the default value is None.

(6) shadow parameter

The shadow parameter controls whether to display a shadow behind the legend. The default value is None.

(7) fancybox parameters

The fancybox parameter controls whether to set a rounded border for the legend. The default value is None.

Note: If the label displayed in the legend has been pre-specified through the label parameter when drawing using the pyplot drawing function, you can directly call the legend() function to add the legend; if the label applied to the legend is not pre-specified, then call legend() later. ) function, just pass values for the parameters handles and labels. The sample code is as follows:

ax.plot( [1, 2, 3] , label= ‘Inline label’)

ax.legend()

#or

ax. legend( (linel, line2, line3), (‘ label1 ‘, ‘ label2 ‘, ‘ label3 ‘))

1.1.4 Display grid
1. Display the grid of the specified style

Use the grid() function in the pyplot module to display the grid. The syntax format of the grid() function is as follows:

grid (b=None, which= ‘major’, axis=’both’, ** kwargs) # b=visible

The meanings of the commonly used parameters of this function are as follows:

b: Indicates whether to display the grid. If other keyword parameters are provided, the b parameter is set to True.

which: indicates the type of display grid, supporting three types: major, minor, and both. The default is major.

axis: Indicates which direction of the grid is displayed. This parameter supports three options: both, x and y. The default is both.

linewidth or lw: Represents the width of grid lines.

Additionally, the grid can be displayed using the grid() method of the Axes object. It should be noted that if the coordinate axis has no scale, the grid cannot be displayed.

1.1.5 Add comment text
1. Add directional annotation text

Use the annotate() function provided in the pyplot module to add directional annotation text to the chart. The syntax format of this function is as follows:

annotate(s, xy, *args, **kwargs)

The meanings of common parameters of this function are as follows:

s: represents the content of the comment text.

xy: Represents the coordinate position of the annotated point, receiving tuples (x, y).

xytext: Represents the coordinate position of the annotation text, receiving tuples (x, y).

xycoords: represents the coordinate system of xy. The default value is “data”, which represents the same coordinate system as the line chart.

arrowprops: A dictionary of properties indicating arrows.

bbox: A dictionary of border attributes representing the annotation text.

The arrowprops parameter receives a dictionary containing several keys, and controls the display of arrows by adding key-value pairs to the dictionary. Common keys for controlling arrows include width, headwidth, headlength, shrink, arrowstyle, etc. The key arrowstyle represents the type of arrow. The value and type corresponding to this key are shown in Figure 3-14.

2. Combine the above knowledge points and use code to run the examples

#Requirement: Draw a chart containing sine curves and cosine curves. The specific requirements are as follows:
# (1) The style of the sinusoidal curve: red, line width is 1.0;
# (2) Cosine curve style: blue, line width 1.0, transparency 0.5;
# (3) The scale labels of the x-axis are “-π”, “-π/2”, “0”, “π/2”, “-π”;
# (4) Add directional annotation text at the position of x=1, y=np.cos(1);
# (5) Fill the area enclosed by the sine curve and the cosine curve with green, with a transparency of 0.25.

3. The sample code is as follows:

# 1. Import the Python library named "numpy" and use the alias "np" to reference the library

import numpy as np

# 2. Import matplotlib.pyplot library

import matplotlib.pyplot as plt

# 3. Set to support Chinese character display (fixed code, no need to change)
# matplotlib does not support Chinese display by default. If we need to display Chinese, we need to do some additional settings.

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# When using mpl.rcParams to set parameters, it is a global setting

# 4. Prepare data

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y_cos, y_sin = np.cos(x), np.sin(x)

# 5. Draw polyline

# Cosine curve style: blue, line width 1.0, transparency 0.5;
lines1 = plt.plot(x, y_cos, color='b',lw=1.0, alpha=0.5)

# The style of the sinusoidal curve: red, line width is 1.0;
lines2 = plt.plot(x, y_sin, color='r',lw=1.0)

kinds = ['cos','sin']

# 6. Customization of chart auxiliary elements (chart title, scale labels, legend, grid, directional annotation text)

plt.title("Cos & amp; Sin")

# The scale labels of the x-axis are "-π", "-π/2", "0", "π/2", "-π";
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
           [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'])

plt.yticks([-1.00, -0.50, 0.00, 0.50, 1.00])

plt.legend(kinds, loc='upper left')

plt.grid( visible=True )

# Add directional annotation text at the position of x=1, y=np.cos(1);
plt.annotate("cos(1)", xy=( 1.0, np.cos(1)), xytext=( 1.03, 0.8),
            arrowprops = dict(arrowstyle="->"))

#7. Chart style beautification (fill color)

# Fill the area enclosed by the sine curve and the cosine curve with green, with a transparency of 0.25
plt.fill_between(x, y_cos, y_sin, y_cos > y_sin, color='g', alpha=0.25)

# 8. Chart display

plt.show()

4. Chart formation style

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeHomepageOverview 382828 people are learning the system