Drawing and beautifying skills of [Python] Matplotlib chart

itread01 2021-02-22 11:56:47
drawing beautifying skills python matplotlib


[TOC]## Draw multiple charts on one canvas Matplotlib When the module is drawing a diagram , Set up a canvas first , Then display the chart drawn in the canvas . If you want to draw multiple charts in one canvas , have access to subplot() Function divides the canvas into several areas , Then draw different charts in each area .subplot() The argument of the function is 3 Integer number :+ The first 1 A number means dividing the whole canvas into several lines ;+ The first 2 A number means that the whole canvas is divided into several columns ;+ The first 3 A number represents the number of areas in which to plot the chart , The numbering of areas is from left to right 、 From top to bottom , From 1 Start numbering . The demo code is as follows :```pythonimport matplotlib.pyplot as plt# If there are Chinese characters in the value , You must add these two lines of code before drawing the diagram plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']plt.rcParams['axes.unicode_minus'] = Falsex = ['1 month ', '2 month ', '3 month ', '4 month ', '5 month ', '6 month ', '7 month ', '8 month ', '9 month ', '10 month ', '11 month ', '12 month ']y = [50, 45, 65, 76, 75, 85, 55, 78, 86, 89, 94, 90]plt.subplot(2, 2, 1)plt.pie(y, labels = x, labeldistance = 1.1, startangle = 90, counterclock = False)plt.subplot(2, 2, 2)# Arguments width Used to set the width of the column , The default value is 0.8. If set to 1, The columns will be closely connected ; If set to greater than 1 The number of , The columns will overlap each other plt.bar(x, y, width = 0.5, color = 'r')plt.subplot(2, 2, 3)# Arguments color Used to set the filling color of the column , See the following description for specific values plt.stackplot(x, y, color = 'r')plt.subplot(2, 2, 4)plt.plot(x, y, color = 'r', linestyle = 'solid', linewidth = 2, marker = 'o', markersize = 10)plt.show()``` Output results :![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220161523307-1212189385.png) It is defined by the English word of color name or its abbreviation 8 Two basic colors , See :![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220162749196-934552246.png)## Add chart elements ```pythonimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']plt.rcParams['axes.unicode_minus'] = Falsex = ['1 month ', '2 month ', '3 month ', '4 month ', '5 month ', '6 month ', '7 month ', '8 month ', '9 month ', '10 month ', '11 month ', '12 month ']y = [50, 45, 65, 76, 75, 85, 55, 78, 86, 89, 94, 90]# It's labeled here plt.bar(x, y, width=0.6, color='r', label=' Sales ( Ten thousand yuan )')# The title is added here ,loc It could be right and leftplt.title(label=' Sales comparison chart ', fontdict={'family': 'KaiTi', 'color': 'k', 'size': 30}, loc='center')# Labels in coordinates plt.xlabel(' month ', fontdict={'family': 'SimSun', 'color': 'k', 'size': 20}, labelpad=20) plt.ylabel(' Sales ', fontdict={'family': 'SimSun', 'color': 'k', 'size': 20}, labelpad=20) # legend() Function is used to add a legend plt.legend(loc='upper left', fontsize=15)# zip() Functions are used to use iteratable objects as arguments , Package the corresponding elements in the object into tuples , And then return a list of these tuples .for a,b in zip(x, y): # text() The function is to add text at the specified position in the chart coordinate system . Arguments ha yes horizontalalignment Short for , There should be va plt.text(x=a, y=b, s=b, ha='center', va='bottom', fontdict={'family': 'KaiTi', 'color': 'k', 'size': 20})plt.show()``` Output results ![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220163727288-1207960104.png)## A bubble chart is a chart that shows the relationship between three variables , In fact, it is upgraded and transformed on the basis of scatter diagram , In the original x Coordinates and y Coordinates are based on two variables , Introduce a third variable , And it's represented by the size of the bubble .```pip install openpyxl``` Product sales statistics .xls Content | Product name | Sales volume ( Pieces of ) | Sales ( element ) | Gross profit margin (%) || ---- | ------ | ------ | ------ || Jeans | 125 | 6800 | 30 || Dress | 278 | 5600 | 20 || Sweatpants | 366 | 7800 | 35 || shorts | 452 | 5800 | 10 || Short skirt | 365 | 5400 | 50 || Suspenders | 258 | 10000 | 22 || skirt | 369 | 3600 | 15 || Wide leg pants | 566 | 7800 | 8 | The code is as follows :```pythonimport matplotlib.pyplot as pltimport pandas as pdplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']plt.rcParams['axes.unicode_minus'] = Falsedata = pd.read_excel(' Product sales statistics .xls')n = data[' Product name ']x = data[' Sales volume ( Pieces of )']y = data[' Sales ( element )']z = data[' Gross profit margin (%)']plt.scatter(x, y, s=z * 300, color='r', marker='o')plt.xlabel(' Sales volume ( Pieces of )', fontdict={'family': 'Microsoft YaHei', 'color': 'k', 'size': 20}, labelpad=20)plt.ylabel(' Sales ( element )', fontdict={'family': 'Microsoft YaHei', 'color': 'k', 'size': 20}, labelpad=20)plt.title(' Sales volume 、 Sales vs. gross margin ', fontdict={'family': 'Microsoft YaHei', 'color': 'k', 'size': 30}, loc='center')for a, b, c in zip(x, y, n): plt.text(x=a, y=b, s=c, ha='center', va='center', fontsize=15, color='w')plt.xlim(50, 600)plt.ylim(2900, 11000)plt.show()``` Output results :![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220165618772-1044548018.png)## Combination chart combination chart refers to drawing multiple charts in a coordinate system , Its implementation is also very simple , In the use of Matplotlib The function in the module sets multiple groups when drawing a chart y Coordinate value is enough . Sales performance table .xls| month | Sales ( Ten thousand yuan ) | Year on year growth rate || ---- | ------- | ----- || 1 month | ¥36.00 | 10% || 2 month | ¥25.00 | 8% || 3 month | ¥36.12 | 20% || 4 month | ¥69.30 | 50% || 5 month | ¥26.90 | 15% || 6 month | ¥32.00 | 11% || 7 month | ¥45.00 | 26% || 8 month | ¥56.00 | 13% || 9 month | ¥25.60 | 4% || 10 month | ¥36.21 | 5% || 11 month | ¥25.00 | 7% || 12 month | ¥59.00 | 30% |```pythonimport pandas as pdimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']plt.rcParams['axes.unicode_minus'] = Falsedata = pd.read_excel(' Sales performance table .xlsx')x = data[' month ']y1 = data[' Sales ( Ten thousand yuan )']y2 = data[' Year on year growth rate '] plt.bar(x, y1, color = 'c', label = ' Sales ( Ten thousand yuan )') plt.legend(loc = 'upper left', fontsize = 15) # Use twinx() Function adds a secondary axis to the graph plt.twinx() plt.plot(x, y2, color = 'r', linewidth = 3, label = ' Year on year growth rate ') plt.legend(loc = 'upper right', fontsize = 15) plt.show()``` Output results :![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220170456784-1838638597.png)## Histograms are used to show the distribution of data , Use Matplotlib In the module hist() Function can draw histogram [ Customer age Statistics .zip](https://files.cnblogs.com/files/feily/%E5%AE%A2%E6%88%B7%E5%B9%B4%E9%BE%84%E7%BB%9F%E8%AE%A1%E8%A1%A8.zip)```pythonimport pandas as pdimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']plt.rcParams['axes.unicode_minus'] = Falsedata = pd.read_excel(' Customer age Statistics .xlsx')x = data[' Age ']plt.hist(x, bins = 9)plt.xlim(15, 60)plt.ylim(0, 40)plt.title(' Age distribution histogram ', fontsize = 20)plt.xlabel(' Age ')plt.ylabel(' Number ')plt.grid(b = True, linestyle = 'dotted', linewidth = 1)plt.show()``` Output results ![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220172015289-863829486.png)## Radar chart radar chart can compare and analyze multiple indicators at the same time . The chart can be seen as one or more closed broken lines , therefore , Use the plot() Functions can also be used to draw radar graphs . Statistical table of automobile performance index score .xlsx| Performance evaluation index | A brand | B brand | C brand || ------ | ---- | ---- | ---- || Motivation | 1 | 3 | 10 || Fuel economy | 2 | 6 | 7 || Braking | 1 | 10 | 5 || Handling stability | 3 | 10 | 2 || Ride comfort | 2 | 6 | 1 || Through sex | 4 | 7 | 2 || Security | 8 | 2 | 1 || Environmental protection | 9 | 1 | 3 || Convenience | 10 | 3 | 0 || Comfort | 8 | 2 | 1 || Economy | 4 | 1 | 10 || Capacity | 2 | 2 | 8 | The code is as follows :```pythonimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False data = pd.read_excel(' Statistical table of automobile performance index score .xlsx')data = data.dropna(axis=1)data = data.set_index(' Performance evaluation index ')data = data.Tdata.index.name = ' brand 'def plot_radar(data, feature): columns = [' Motivation ', ' Fuel economy ', ' Braking ', ' Handling stability ', ' Ride comfort ', ' Through sex ', ' Security ', ' Environmental protection ', ' Convenience ', ' Comfort ', ' Economy ', ' Capacity '] colors = ['r', 'g', 'y'] # Set the angle of the radar chart , Used to bisect a plane # linspace(1,10,x) establish 1-10 The arithmetic array of , The number is x, Presupposition 50 One ;endpoint Argument specifies whether to include the final value , The default value is True, Including the final value . angles = np.linspace(0.1 * np.pi, 2.1 * np.pi, len(columns), endpoint = False) # Close the radar map angles = np.concatenate((angles, [angles[0]])) # figsize: Appoint figure The width and height of , It's in inches ; figure = plt.figure(figsize = (6, 6)) # Set to polar format ;subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw) Create a single subgraph , The following two sentences have the same effect ax = figure.add_subplot(111, polar=True) # ax = figure.add_subplot(1, 1, 1, projection = 'polar') for i, c in enumerate(feature): stats = data.loc[c] stats = np.concatenate((stats, [stats[0]])) ax.plot(angles, stats, '-', linewidth = 2, c = colors[i], label = str(c)) ax.fill(angles, stats, color = colors[i], alpha = 0.75) # bbox_to_anchor This argument , You can put the legend on the outside of the diagram # bbox_to_anchor: Express legend The location of , The former means left and right , The latter means up and down . # When using this argument .loc Will no longer function normally ,ncol=3 The legend is shown in three columns . ax.legend(loc = 4, bbox_to_anchor = (1.15, -0.07)) # Set the polar range ax.set_ylim(0,10) # ax.set_yticklabels([2, 4, 6, 8, 10]) # Add a label for each trait columns = np.concatenate((columns, [columns[0]])) ax.set_thetagrids(angles*180/np.pi, columns, fontsize = 12) # New title plt.title(' Radar chart of automobile efficiency index ') plt.show() return figurefigure = plot_radar(data, ['A brand ', 'B brand ', 'C brand '])# figure = plot_radar(data, ['B brand '])```![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220190834095-1285051144.png)## Tree view tree view through the area of the rectangle 、 The arrangement and color directly show the data proportion relationship of multiple projects . To draw the chart , Need to be used in combination Matplotlib Module and squarify Module .```pythonimport squarify as sfimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']plt.rcParams['axes.unicode_minus'] = Falsex = [' Shanghai ', ' Beijing ', ' Chongqing ', ' Chengdu ', ' nanjing ', ' Qingdao ', ' Changsha ', ' Wuhan ', ' Shenzhen '] y = [260, 45, 69, 800, 290, 360, 450, 120, 50] colors = ['lightgreen', 'pink', 'yellow', 'skyblue', 'cyan', 'silver', 'lightcoral', 'orange', 'violet']percent = ['11%', '2%', '3%', '33%', '12%', '15%', '18%', '5%', '2%']chart = sf.plot(sizes = y, label = x, color = colors, value = percent, edgecolor = 'white', linewidth = 2)plt.title(label = ' Distribution and proportion of city sales ',fontdict = {'family' : 'KaiTi', 'color' : 'k', 'size' : 25})plt.axis('off')plt.show()```![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220191046317-92980110.png)## Box chart a box chart is a statistical chart used to show the distribution of data , It's named after the shape of a box . Use Matplotlib In the module boxplot() Functions can be used to draw box graphs . Information | date | Chengdu | Shanghai | Beijing | Chongqing | nanjing || ----- | ---- | ---- | ---- | ---- | ---- || 1 month 1 Japan | 25 | 50 | 52 | 25 | 50 || 1 month 2 Japan | 12 | 58 | 56 | 26 | 56 || 1 month 3 Japan | 26 | 60 | 100 | 78 | 58 || 1 month 4 Japan | 23 | 78 | 125 | 45 | 87 || 1 month 5 Japan | 18 | 36 | 108 | 46 | 50 || 1 month 6 Japan | 15 | 69 | 100 | 50 | 60 || 1 month 7 Japan | 19 | 41 | 85 | 53 | 26 || 1 month 8 Japan | 20 | 52 | 85 | 61 | 36 || 1 month 9 Japan | 26 | 53 | 87 | 87 | 69 || 1 month 10 Japan | 27 | 69 | 86 | 25 | 78 || 1 month 11 Japan | 28 | 78 | 45 | 16 | 75 || 1 month 12 Japan | 54 | 80 | 78 | 69 | 80 || 1 month 13 Japan | 50 | 52 | 73 | 68 | 81 || 1 month 14 Japan | 51 | 26 | 62 | 45 | 45 || 1 month 15 Japan | 52 | 28 | 65 | 40 | 65 || 1 month 16 Japan | 36 | 57 | 90 | 50 | 63 || 1 month 17 Japan | 38 | 56 | 96 | 60 | 69 || 1 month 18 Japan | 45 | 89 | 94 | 36 | 64 || 1 month 19 Japan | 40 | 84 | 25 | 52 | 65 || 1 month 20 Japan | 41 | 85 | 36 | 54 | 45 || 1 month 21 Japan | 26 | 80 | 68 | 58 | 52 || 1 month 22 Japan | 29 | 75 | 78 | 56 | 59 || 1 month 23 Japan | 36 | 50 | 70 | 52 | 80 || 1 month 24 Japan | 33 | 25 | 52 | 57 | 29 || 1 month 25 Japan | 31 | 36 | 51 | 69 | 36 || 1 month 26 Japan | 15 | 64 | 58 | 54 | 29 || 1 month 27 Japan | 18 | 56 | 68 | 25 | 90 || 1 month 28 Japan | 25 | 54 | 78 | 36 | 78 || 1 month 29 Japan | 14 | 50 | 90 | 78 | 71 || 1 month 30 Japan | 39 | 44 | 95 | 56 | 75 || 1 month 31 Japan | 48 | 49 | 84 | 25 | 76 |```import pandas as pdimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']plt.rcParams['axes.unicode_minus'] = Falsedata = pd.read_excel('1 Monthly sales statistics .xlsx')x1 = data[' Chengdu ']x2 = data[' Shanghai ']x3 = data[' Beijing ']x4 = data[' Chongqing ']x5 = data[' nanjing ']x = [x1, x2, x3, x4, x5]labels = [' Chengdu ', ' Shanghai ', ' Beijing ', ' Chongqing ', ' nanjing ']# Arguments vert Used to set the direction of a box graph ,True It means vertical display ,False Show horizontally ; Arguments showmeans Used to set whether to display the mean value ,True Shows the mean value ,False The mean value is not shown .plt.boxplot(x, vert = True, widths = 0.5, labels = labels, showmeans = True )plt.title(' By Region 1 Box chart of monthly sales ', fontsize = 20)plt.ylabel(' Sales ( Ten thousand yuan )')plt.show()```![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220193217166-1848719514.png) In the box 5 Two horizontal lines and 1 The meaning of the dots is as follows :+ Lower limit : The minimum of all data ;+ The lower quartile : Also known as “ The first quartile ”, It means to arrange all the data from small to large 25% Value ;+ Median : Also known as “ The second quartile ”, It means to arrange all the data from small to large 50% Value ;+ The upper quartile : Also known as “ The third quartile ”, It means to arrange all the data from small to large 75% Value ;+ ceiling : The maximum of all data ;+ Point : The average of all data .## Rose chart rose chart can reflect data of multiple dimensions , It turns a column chart into a pie chart , With the same central angle , Show the index size by sector length . To draw a rose , Also need to use the method of drawing column chart bar() Function .```pythonimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False# Set the wind speed distribution to 4 Intervals index = ['0~0.5', '0.6~2.0', '2.1~4.0', '4.1~6.0']# Set 16 In one direction columns = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']# seed() Functions are used to generate the same random number np.random.seed(0)# Build a 4 That's ok 16 Column DataFrame, The information is 30~300 Random number in range , The row label is 6 The wind speed distribution range set by the line code , The column label is number 7 The direction set by the line code .data = pd.DataFrame(np.random.randint(30, 300, (4, 16)), index = index, columns = columns)N = 16# Generate 16 The angle value in two directions theta = np.linspace(0, 2 * np.pi, N, endpoint = False)# Used to calculate the width of a sector width = np.pi / N labels = list(data.columns) plt.figure(figsize = (6, 6))ax = plt.subplot(1, 1, 1, projection = 'polar')for i in data.index: radius = data.loc[i] # Use bar() Function to draw... In the rose diagram 16 Root column , That's the fan , Arguments bottom Used to set the position of the bottom of each column , This is set to 0.0, It means to draw from the center of the circle . ax.bar(theta, radius, width = width, bottom = 0.0, label = i, tick_label = labels)# Set 0° My direction is “N”, The north ax.set_theta_zero_location('N') # Set the columns to be arranged counter clockwise ax.set_theta_direction(-1) plt.title(' Rose chart of wind speed frequency in all directions ', fontsize = 20)plt.legend(loc = 4, bbox_to_anchor = (1.3, 0.2)) plt.show()```![](https://img2020.cnblogs.com/blog/2200001/202102/2200001-20210220193807032-15218021
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210221003120619x.html

  1. 27000 stars! The most comprehensive collection of Python design patterns
  2. python day3
  3. python day3
  4. Commonly used data operation functions of Python
  5. (数据科学学习手札108)Python+Dash快速web应用开发——静态部件篇(上)
  6. (learning notes of data science 108) Python + dash rapid web application development -- static components (I)
  7. (数据科学学习手札108)Python+Dash快速web应用开发——静态部件篇(上)
  8. (learning notes of data science 108) Python + dash rapid web application development -- static components (I)
  9. [Python] Matplotlib 图表的绘制和美化技巧
  10. Drawing and beautifying skills of [Python] Matplotlib chart
  11. [Python] Matplotlib 图表的绘制和美化技巧
  12. Drawing and beautifying skills of [Python] Matplotlib chart
  13. Virtual environment of Python project
  14. 翻译:《实用的Python编程》02_01_Datatypes
  15. Translation: practical Python Programming 02_ 01_ Datatypes
  16. 翻译:《实用的Python编程》02_01_Datatypes
  17. 翻译:《实用的Python编程》02_01_Datatypes
  18. Translation: practical Python Programming 02_ 01_ Datatypes
  19. Translation: practical Python Programming 02_ 01_ Datatypes
  20. Python 3 入门,看这篇就够了
  21. Python 3 entry, see this is enough
  22. 华为大佬打造的400集Python视频学起来,学完万物皆可爬
  23. 400 episodes of Python video created by Huawei boss
  24. django之csrf_exempt解决跨域请求的问题
  25. CSRF of Django_ Exempt solves the problem of cross domain requests
  26. 1.7 万 Star!一个简单实用的 Python 进度条库
  27. 17000 stars! A simple and practical Python progress bar library
  28. Python爬虫:设置Cookie解决网站拦截并爬取蚂蚁短租
  29. Python crawler: setting cookie to solve website interception and crawling ant short rent
  30. Python-Net编程
  31. Python net programming
  32. 学习Python数学英语基础重要吗?Python教程!
  33. Is it important to learn the basics of math and English in Python!
  34. Python数据分析常用库有哪些?Python学习!
  35. What are the common libraries for Python data analysis? Learn Python!
  36. win 创建python虚拟环境
  37. Creating Python virtual environment with win
  38. In order to automatically collect B station barrage, I developed a tool in Python
  39. 用Python编程语言来实现阿姆斯特朗数的检查
  40. Using python programming language to check Armstrong number
  41. Python中的解决中文字符编码的问题
  42. Solving the problem of Chinese character coding in Python
  43. Translation: practical Python Programming 02_ 01_ Datatypes
  44. Installation and use of Python and tensorflow in win10 environment (Python version 3.6, tensorflow version 1.6)
  45. Python series 46
  46. Linux安装Python3
  47. 【python接口自动化】- 正则用例参数化
  48. Python RestFul Api 设计
  49. filecmp --- 文件及目录的比较│Python标准库
  50. Installing python3 on Linux
  51. [Python] Matplotlib 圖表的繪製和美化技巧
  52. (資料科學學習手札108)Python+Dash快速web應用開發——靜態部件篇(上)
  53. 翻譯:《實用的Python程式設計》02_01_Datatypes
  54. 【python接口自动化】- 正则用例参数化
  55. 翻译:《实用的Python编程》02_02_Containers
  56. 两年Java,去字节跳动写Python和Go
  57. [Python interface automation] - regular use case parameterization
  58. Python restful API design
  59. 翻译:《实用的Python编程》02_02_Containers
  60. 两年Java,去字节跳动写Python和Go