Home Backend Development Python Tutorial Detailed explanation of python using matplotlib drawing

Detailed explanation of python using matplotlib drawing

Oct 18, 2016 pm 02:12 PM
matplotlib python Drawing Detailed explanation

Matplotlib is python's most famous drawing library. It provides a set of command APIs similar to matlab, which is very suitable for interactive drawing. And it can also be easily used as a drawing control and embedded in GUI applications. Its documentation is quite complete, and there are hundreds of thumbnails in the Gallery page, and they all have source programs after opening them. So if you need to draw a certain type of diagram, just browse/copy/paste on this page and you'll basically be done.

In this article, we use matplotlib to construct the simplest bar step by step to the complex bar. What is the simplest bar? Look at the following statement and you will know how simple it is:

import matplotlib.pyplot as plt 
  
plt.bar(left = 0,height = 1)
plt.show()
Copy after login

Execution effect:

Detailed explanation of python using matplotlib drawing

Yes, just three sentences are enough. It is the simplest drawing statement I have ever seen. First we imported matplotlib.pyplot, then directly called its bar method, and finally used show to display the image. Let me explain the two parameters in bar:

left: The position of the left edge of the column. If we specify 1, then the x value of the left edge of the current column is 1.0

height: This is the height of the column, That is, the value of the Y-axis

left, height can not only use a separate value (in this case it is a column), but can also be replaced by a tuple (in this case it represents multiple rectangles). For example, in the following example:

import matplotlib.pyplot as plt
  
plt.bar(left = (0,1),height = (1,0.5))
plt.show()
Copy after login

Detailed explanation of python using matplotlib drawing

You can see that left = (0,1) means that there are two rectangles in total, the left edge of the first one is 0, and the left edge of the second one is 1. The height parameter is the same.

Of course, you may still think these two rectangles are "too fat". At this point we can set their width by specifying the width parameter of the bar.

import matplotlib.pyplot as plt
  
plt.bar(left = (0,1),height = (1,0.5),width = 0.35)
plt.show()
Copy after login

Detailed explanation of python using matplotlib drawing

At this time, there is another demand. I need to indicate the instructions for the x and y axes. For example, the x-axis is gender and the y-axis is number of people. The implementation is also very simple, look at the code:

import matplotlib.pyplot as plt
  
plt.xlabel(u'性别')
plt.ylabel(u'人数')
plt.bar(left = (0,1),height = (1,0.5),width = 0.35)
plt.show()
Copy after login

Detailed explanation of python using matplotlib drawing

Note that u must be used for Chinese here (it doesn’t seem to be used above 3.0, I use 2.7), because matplotlib only supports unicode. Next, let's illustrate each bar on the x-axis. For example, the first one is "male" and the second one is "female". The usage of

import matplotlib.pyplot as plt
  
plt.xlabel(u'性别')
plt.ylabel(u'人数')
  
plt.xticks((0,1),(u'男',u'女'))
  
plt.bar(left = (0,1),height = (1,0.5),width = 0.35)
  
plt.show()
Copy after login

Detailed explanation of python using matplotlib drawing

plt.xticks is similar to the usage of left and height we mentioned earlier. If you have several bars, then it is a tuple of several dimensions. The first is the location of the text, and the second is the specific text description. But there is a problem here. Obviously the position we specified is somewhat "offset", and the ideal state should be in the middle of each rectangle. You can change (0,1)=>( (0+0.35)/2, (1+0.35)/2) but this is more troublesome. We can center the text by directly specifying align="center" in the bar method

import matplotlib.pyplot as plt
  
plt.xlabel(u'性别')
plt.ylabel(u'人数')
  
plt.xticks((0,1),(u'男',u'女'))
  
plt.bar(left = (0,1),height = (1,0.5),width = 0.35,align="center")
  
plt.show()
Copy after login

Detailed explanation of python using matplotlib drawing

Next, we can also add a title to the icon.

plt.title(u"性别比例分析")
Copy after login

Detailed explanation of python using matplotlib drawing

Of course, the legend is also indispensable:

import matplotlib.pyplot as plt
  
plt.xlabel(u'性别')
plt.ylabel(u'人数')
  
  
plt.title(u"性别比例分析")
plt.xticks((0,1),(u'男',u'女'))
rect = plt.bar(left = (0,1),height = (1,0.5),width = 0.35,align="center")
  
plt.legend((rect,),(u"图例",))
  
plt.show()
Copy after login

Detailed explanation of python using matplotlib drawing

Note the legend method here, the parameters inside must be tuples. Even if you only have one legend, it will not display correctly.

Next, we can also mark the specific point Y value of each rectangle. Here, we need to use a general method:

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2., 1.03*height, '%s' % float(height))
Copy after login

The parameters of plt.text are: x coordinate, y coordinate, and the text to be displayed. So, the calling code is as follows:

import matplotlib.pyplot as plt
  
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2., 1.03*height, '%s' % float(height))
  
plt.xlabel(u'性别')
plt.ylabel(u'人数')
  
  
plt.title(u"性别比例分析")
plt.xticks((0,1),(u'男',u'女'))
rect = plt.bar(left = (0,1),height = (1,0.5),width = 0.35,align="center")
  
plt.legend((rect,),(u"图例",))
autolabel(rect)
  
plt.show()
Copy after login

Detailed explanation of python using matplotlib drawing

At this point, the graphic is basically complete, but you can see that you have a rectangle close to the top, which doesn’t look very good. It would be best to come out with some distance. I didn't find any specific properties for this setting. However, I did it with a little trick. It is the yerr parameter of the bar attribute. Once this parameter is set, there will be a vertical line on the corresponding rectangle. I don't know what it does. But when I set this value to a very small value, the space above is automatically vacated. As shown in the picture:


rect = plt.bar(left = (0,1),height = (1,0.5),width = 0.35,align="center",yerr=0.000001)

Detailed explanation of python using matplotlib drawing

for the left and right sides I haven’t found whether I can leave a blank space (the xerr parameter doesn’t work)


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles