3.2.2 Setting scale range and scale label
When drawing a chart, the scale range and scale label of the coordinate axis are directly related to the distribution of the data, that is, the coordinateThe scale range of the axis depends on the maximum and minimum values of the data. If no data is specified when drawing with matplotlib,The range of x- axis and y -axis are both 0.05 ~ 1.05, and the scale labels are [-0.2, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2]; if specifiedThe data of the x- axis and y- axis are determined , and the scale range and scale label will change as the data changes. matplotlib provides heavyThe method of newly setting the scale range and scale label of the coordinate axis will be introduced separately below.1. Set scale rangeUse the xlim() and ylim() functions of 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=None,xmax=None)The meanings of common parameters of this function are as follows.·left : Indicates the left digit of the x- axis scale value range.·right : Indicates the right digit of 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 : Indicates the minimum value of the x- axis scale.xmax : Indicates 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 labelsUse the xticks() and yticks() functions of the pyplot module to set or get the tick mark positions of the x- axis and y -axis respectivelyand tick labels. The syntax of the xticks() function is as follows:xticks(ticks=None, labels=None, ** kwargs)The ticks parameter of this function indicates the list of positions displayed by the scale, and it can also be set to an empty list to disable the ticks of the x- axisdegree; labels indicates the label list of 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,Use the set_xticklabels() or set_yticklabels() method to set the tick labels for the x- axis or y -axis respectively.Set the scale range and scale label of the axis in the sine and cosine plots drawn in Section 3.2.1, the added codeas follows.#Set the scale range and scale label of the x- axisplt.xlim(x.min() * 1.5, x.max() * 1.5)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$'])Run the program, the effect is shown in Figure 3-4.3.2.3 Example 1: 2019 China Movie Box Office RankingIf you have some free time, going to the theater to watch movies would be a good option. Nowadays, watching movies has become aIt is not only a visual enjoyment, but also a spiritual feast, which makes people relax. 2019In 2019, many movies with good reputation were released in China. After counting the total box office of each movie, it is concluded that the 2019 Chinese movieThe top 15 movie box office rankings are shown in Table 3-1.
According to the data in Table 3-1, use the data in the "Movie Name" column as the scale label of the y- axis, and set the "Total Box Office (100 million yuan)"
One column of data is used as the value corresponding to the scale label, and barh() is used to draw the top 15 of the Chinese movie box office list in 2019Bar chart, and add labels and scale labels for the axis of the bar chart, the specific code is as follows.In [2]:# 01_film_rankingsimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams["axes.unicode_minus"] = Falselabels = [" Nezha: The Devil Boy Comes into the World ", " Wandering Earth ", " Avengers 4: Endgame "," Crazy Alien ", " Flying Speed ", " Heroes of Fire ", " Spider-Man : Far From Home "," Fast and Furious : Special Operations ", " Sweeping Drugs 2 : Showdown ", " Bumblebee ", " Captain Marvel "," A Story More Sad Than Sad ", " Godzilla 2: King of the Monsters ", " Alita : Battle Angel "," Galaxy Tutorial "]bar_width = [48.57, 46.18, 42.05, 21.83, 17.03, 16.70, 14.01, 13.84,12.85, 11.38, 10.25, 9.46, 9.27, 8.88, 8.64]y_data = range(len(labels))fig = plt.figure()ax = fig.add_subplot(111)ax.barh(y_data, bar_width, height=0.2, color='orange')#Set the labels of the x- axis and y - axisax.set_xlabel(" Total box office ( 100 million yuan )")ax.set_ylabel(" movie name ")#Set the tick mark position and tick label of the y- axisax.set_yticks(y_data)ax.set_yticklabels(labels)plt.show()Run the program, the effect is shown in Figure 3-5.In Figure 3-5, the x- axis labels are at the bottom and the y- axis labels are on the left. As can be seen from Figure 3-5, the movie "Nezha:Devil's Birth topped the box office total, "The Wandering Earth" came in second, and "Avengers: Endgame" topped the list.It ranked third at the box office.
3.3 Add title and legend3.3.1 Add titleThe title of the chart represents the name of the chart, and is generally located at the top of the chart and aligned with the center of the chart, which can quickly let readers knowUnderstand what the diagram is trying to illustrate. In matplotlib, you can directly use the title() function of the pyplot module to add chart titles,The syntax of the title() function is as follows:title(label, fontdict=None, loc='center', pad=None, ** kwargs)The meanings of common parameters of this function are as follows.· label : Indicates the text of the title.fontdict : Indicates a dictionary that controls the style of the title text.·loc : Indicates the alignment style of the title, including three values of 'left', 'right' and 'center', the default value is 'center',That is, the title is displayed in the center.pad : Indicates the distance between the title and the top of the chart, the default is None.In addition, the Axes object can also add the title of the chart using the set_title() method.Add the title "Sinusoid and Cosine Curve" to the sine and cosine plots drawn in Section 3.2.2 and add the following code.#add titleplt.title(" Sine and cosine curves ")Run the program, the effect is shown in Figure 3-6.3.3.2 Add legendThe legend is a block diagram that lists the identification methods of each group of graphic data. It is composed of two parts: the legend identification and the legend item., where the legend mark is the pattern representing each group of graphics; the legend item is the name (description text) corresponding to the legend mark. whenWhen matplotlib draws a chart containing multiple sets of graphics, a legend can be added to the chart to help users clarify what each set of graphics represents
meaning.In matplotlib, you can directly use the legend() function of the pyplot module to add a legend, and the syntax format of the legend() functionAs follows:legend(handles, labels, loc, bbox_to_anchor, ncol, title, shadow,fancybox, * args, ** kwargs)The common parameters of this function are introduced as follows.(1) handles and labels parametersThe handles parameter represents a list of graphic labels, and the labels parameter represents a list of legend entries. Note requiredNote that the handles and labels parameters should receive lists of the same length, if the received lists are of different lengths, the longerThe list is truncated so that the longer list is equal in length to the shorter list.(2) loc parameterThe loc parameter is used to control the position of the legend in the chart. This parameter supports both string and numeric values. EachThe descriptions of these values and their corresponding legend positions are shown in Table 3-2.(3) bbox_to_anchor parameterThe bbox_to_anchor parameter is used to control the layout of the legend, which receives a tuple containing two values, whereThe first value is used to control the horizontal position of the legend display, the larger the value, the more right the legend display position; the second valueThe 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 parameterThe ncol parameter indicates the number of columns of the legend, and the default value is 1.(5) title parameterThe title parameter indicates the title of the legend, and the default value is None.(6) shadow parameterThe shadow parameter controls whether to display a shadow behind the legend, the default value is None.(7) fancybox parameterThe fancybox parameter controls whether to set a rounded border for the legend, the default value is None.
If the label displayed in the legend has been specified in advance through the label parameter when using the pyplot drawing function, thenYou can directly call the legend() function to add a legend; if the label applied to the legend is not specified in advance, then callWhen using the legend() function, just pass values to the parameters handles and labels. The sample code is as follows.ax.plot([1, 2, 3], label='Inline label')ax.legend()# orax.legend((line1, line2, line3), ('label1', 'label2', 'label3'))Add a legend to the sine and cosine graphs drawn in section 3.3.1, the added code is as follows.lines = plt.plot(x, y1, x, y2)#add legendplt.legend(lines, [' sine ', ' cosine '], shadow=True, fancybox=True)Run the program, the effect is shown in Figure 3-7.
Python data visualization - customization of chart auxiliary elements
Guess you like
Origin blog.csdn.net/qq_43416206/article/details/132262760
Ranking