3.6.3 Python data visualization - customization of chart auxiliary elements

3.6.3 Example 5: GMV of Alibaba’s Taobao and Tmall platforms in fiscal year 2013-2019 (Tim

annotated text)

Although the column chart can reflect the amount of each group of data through the height of the column, it is still impossible for the user to accurately know
A specific value. For this reason, column charts are often used in conjunction with annotation text, labeling specific values ​​at the top of the column. 2.2.2
The column chart in the section example describes the GMV of Alibaba Taobao and Tmall platforms, but the rectangular bars in the figure lack specific data.
Value, so here will add undirected annotation text in the column chart, the code is as follows.
In [6]:
# 05_taobao_and_tianmao_GMV
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.arange(1, 8)
y = np.array([10770, 16780, 24440, 30920, 37670, 48200, 57270])
bar_rects = plt.bar(x, y, tick_label=["FY2013", "FY2014", "FY2015",
             "FY2016", "FY2017", "FY2018", "FY2019"], width=0.5)
# Add undirected comment text
def autolabel(rects):
  """Appends a text label above each bar to show its height"""
  for rect in rects:
    height = rect.get_height() # Get the height of each rectangle
    plt.text(rect.get_x() + rect.get_width() / 2, height + 300,
         s='{}'.format(height),
         ha='center', va='bottom')
autolabel(bar_rects)
plt.ylabel('GMV (100 million yuan)')
plt.show()
Run the program, the effect is shown in Figure 3-17.
Compared with Figure 2-6, the column chart in Figure 3-17 adds y -axis labels and comment text to help users know exactly
The value corresponding to each bar. a8e87b9c9d9a499bbc603ebdd2faa01b.png
3.7 Add table
3.7.1 Add a custom style table
matplotlib can draw a variety of charts so that users can discover the regularity between the data. In order to highlight the data
The rules and characteristics of the data are convenient for users to deeply explore the potential meaning of data from the perspective of multivariate analysis. Charts and data tables can be combined
Used in conjunction with a data table to emphasize the values ​​in a certain part of the graph. Adding data tables to charts is provided in matplotlib
Function table(), the syntax of this function is as follows:
table(cellText=None, cellColours=None, cellLoc='right', colWidths=None,
    rowLabels=None, rowColours=None, rowLoc='left', colLabels=None,
    colColours=None, colLoc='center', loc='bottom', bbox=None,
    edges='closed', **kwargs)
The meanings of the commonly used parameters of this function are as follows.
·cellText: Indicates the data in the table cell, which is a two-dimensional list.
·cellColours: Indicates the background color of the cell.
· cellLoc : Indicates the alignment of the cell text, supports 'left', 'right' and 'center' three values, the default value is
'right'。
· colWidths: Indicates the width of each column.
· rowLabels : Indicates the text of the row title.
·rowColours: Indicates the background color of the cell where the row title is located.
· rowLoc: Indicates the alignment of the row title.
· colLabels : Indicates the text of the column headings.
· colColours: Indicates the background color of the cell where the column header is located.
· colLoc : Indicates the alignment of the column headings.

·loc: Indicates the alignment of the table and the drawing area.

In addition, you can also use the table() method of the Axes object to add a data table to the chart. This method is the same as the table() function
The usage is similar and will not be repeated here.
Add a data table to the sine and cosine graphs drawn in Section 3.6.2, and the added code is as follows.
# add table
plt.table(cellText=[[6, 6, 6], [8, 8, 8]],
      colWidths=[0.1] * 3,
      rowLabels=['Row 1', 'Row 2'],
      colLabels=['column 1', 'column 2', 'column 3'], loc='lower right')
Run the program, the effect is shown in Figure 3-18. ce098f5ca17147688fbb17d0697326b3.png
3.7.2 Example 6: Ratio of Ingredients for Jam Bread
A good day starts with breakfast, bread with jam is a common breakfast and loved by everyone, whether it is adults or children
They all love to eat. It is known that the ingredients that need to be prepared for a certain jam bread are shown in Table 3-4. e5b76707c69c463a8ec111a4f2b36168.png

According to the data in Table 3-4, use the data in the "Ingredient Name" column as the legend item, and the ratio of the data in the "Weight" column to the total weight as the data, use pie() to draw a pie chart of the proportion of jam bread ingredients, and set The weight of various ingredients is added to the chart in the form of a data table, which is convenient for users to understand the proportion and weight of various ingredients. The specific code

as follows.

In [7]:
# 06_jam_bread_ingredients
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
kinds = ['flour', 'wheat flour', 'yeast', 'apple sauce', 'egg', 'butter', 'salt', 'sugar']
weight = [250, 150, 4, 250, 50, 30, 4, 20]
total_weight = 0
for i in weight:
  total_weight += i
batching_scale = [i / total_weight for i in weight]
plt.pie(batching_scale, autopct='%3.1f%%')
plt.legend(kinds, loc='upper right', bbox_to_anchor=[1.1, 1.1])
# add table
plt.table(cellText=[weight],
       cellLoc='center',
       rowLabels=['weight (g)'],
       colLabels=kinds,
       loc='lower center')
plt.show()
Run the program, the effect is shown in Figure 3-19.

6061b6edec0949e09a7c617df509a322.png 

In Figure 3-19, the table is below the pie chart. It can be seen from Figure 3-19 that the areas of the blue and red sectors are the largest, indicating that

Applesauce and flour accounted for the largest proportion of the jam bread, both weighing 250 g.

3.8 Chapter Summary
This chapter mainly introduces the customization of the auxiliary elements of the chart, including understanding commonly used auxiliary elements, setting the labels of the coordinate axes,
Set tick ranges and tick labels, add titles and legends, display grids, add guides and regions, add annotations
text, add a table. By studying the content of this chapter, readers can be familiar with the purpose and usage of common chart auxiliary elements, and can

Select suitable auxiliary elements for the diagram.

 
3.9 Exercises
 
1. Fill in the blanks
1. Auxiliary elements of a chart are elements other than those drawn from the data.
2. A legend is a box diagram that lists the graphical modes of each group in the chart.
3. The pointing annotation text is the text explaining the graph through the annotation method.
4. is a line that marks a particular value on an axis.
5. The engine that comes with matplotlib can automatically recognize mathematical strings and parse the mathematical strings into corresponding
    。
2. Judgment questions
1. The legend in matplotlib is always located at the top right of the chart, and its position is immutable. ( )
2. Reference lines provide a reference for comparing graph data with specific values. ( )
3. The label of the axis represents the name of the chart, and is generally located at the top center of the chart. ( )
4. If the axis has no scale, the grid cannot be displayed. ( )
5. The scale range of the axis depends on the maximum and minimum values ​​of the data. ( )
3. Multiple Choice Questions
1. Regarding the auxiliary elements of the chart, the following description is wrong ( ).
A.The title is generally located at the top center of the chart, which can help users understand what the chart is trying to explain
B.A reference area is a line that marks particular values ​​on an axis
C.The legend consists of a legend mark and a legend item, which can help users understand the meaning of each group of graphics
D.Tables are mainly used to emphasize data that is difficult to understand
2. Among the following functions, the axis tick label can be set ( ).
A.xlim()
B.grid ()
C.xticks()
D.axhline()
3. When using the legend() function of pyplot to add a legend, which of the following parameters can control the number of columns of the legend?
(  )
A.place
B.ncol
C.bbox_to_anchor D.fancybox
4. Among the following options, you can add a horizontal reference line with a value of 1.5 to the chart ( ).
A.
plt.axhline(y=1.5, ls='--', linewidth=1.5)
B.
plt.axhline(y=1, ls='--', linewidth=1.5)

 

C.
plt.axvline(x=1.5, ls='--', linewidth=1.5)
D.
plt.axvline(x=1, ls='--', linewidth=1.5)
5. Please read the following piece of code:
r'$\alpha^i < \beta^i$'
The mathematical formula corresponding to the above code is ( ).
A. a i > b i
B. α i > β i
C. α i < β i
D. α i < β i
4. Short answer questions
1. Please briefly describe the difference between directed and undirected comment text.
2. Please list the commonly used auxiliary elements and their functions in charts.
5. Programming questions
1. Customize the column chart based on the first question of programming questions in Chapter 2. The specific requirements are as follows:
(1) Set the label of the y- axis to "Average Grade (Score)";
(2) Set the tick label of the x- axis to be in the middle of the two sets of columns;
(3) Add the title "Average grades of boys and girls in the second year of high school";
(4) Add a legend;
(5) Add note text to the top of each bar, noting the average grade.
2. Customize the pie chart based on Question 2 of Programming Questions in Chapter 2. The specific requirements are as follows:
(1) Add the title "Sales of Pinduoduo Platform Subcategories";
(2) Add a legend and display it in two columns;
(3) Add a table stating the sales by subcategory.

 

Guess you like

Origin blog.csdn.net/qq_43416206/article/details/132262980