Example of using the matplotlib module to draw a data graph in Python

Source: Internet
Author: User
This article describes how to use the matplotlib module to plot data graphs in Python. the matplotlib module is often used to visualize data, for more information, see matplotlib, which is the most famous drawing library in python. It provides a complete set of command APIs similar to matlab and is very suitable for interactive plotting. It can also be easily used as a drawing control and embedded into GUI applications. Its documentation is quite complete, and there are hundreds of thumbnails on the Gallery page. after opening it, all the source programs are available. Therefore, if you want to draw a certain type of graph, you can simply browse, copy, and paste the graph on this page.

In this article, we use matplotlib to build the simplest bar step by step and move forward to the complicated bar. What is the simplest bar? Read the following statement to see how simple it is:

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

Execution result:

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

  1. Left: Position of the left edge of the column. if we specify 1, the x value of the left edge of the current column is 1.0.
  2. Height: this is the height of the column, that is, the value of the y axis.

Left and height can be replaced by a single value (a column at this time) or a tuples (multiple rectangles at this time ). For example, the following example:

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

We can see that left = (0, 1) means there are two rectangles in total, the left edge of the first is 0, and the left edge of the second is 1. The height parameter is the same.
Of course, you may think these two rectangles are too fat. In this case, we can set the width of bar by specifying the width parameter.

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

Now we need to mark the x and y axes. For example, the x axis is gender, and the y axis is the number of people. The implementation is also very simple. check the code:

Import matplotlib. pyplot as plt. xlabel (u'gender') plt. ylabel (u'number') plt. bar (left = (0.5), height = (1, 0.35), width =) plt. show ()

Note that the Chinese character here must use u (3.0 or above does not seem to be needed, I use 2.7), because matplotlib only supports unicode. Next, let's describe each bar on the x axis. For example, the first is "male" and the second is "female ".

Import matplotlib. pyplot as plt. xlabel (u'gender') plt. ylabel (u'number') plt. xticks (0, 1), (u 'male', u 'female ') plt. bar (left = (0.5), height = (1, 0.35), width =) plt. show ()

The usage of plt. xticks is similar to that of left and height we mentioned earlier. If you have several bars, they are the tuples of several dimensions. The first is the text position, and the second is the specific text description. However, there is a problem here. Obviously, the specified position 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 troublesome. You can center the text by directly specifying align = "center" in the bar Method.

Import matplotlib. pyplot as plt. xlabel (u'gender') plt. ylabel (u'number') plt. xticks (0, 1), (u 'male', u 'female ') plt. bar (left = (0.5), height = (1, 0.35), width =, align = "center") plt. show ()

Loading...
Next, we can add a title to the icon.
Plt. title (u "gender ratio analysis ")

Of course, there are still few legends:

Import matplotlib. pyplot as plt. xlabel (u'gender') plt. ylabel (u'number') plt. title (u "gender ratio analysis") plt. xticks (0, 1), (u 'male', u 'female ') rect = plt. bar (left = (0.5), height = (1, 0.35), width =, align = "center") plt. legend (rect,), (u "legend",) plt. show ()

Note that the legend method here must contain tuples. Even if you only have one legend, it is not displayed correctly.
Next, we can mark the specific vertex Y value on 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) where plt. the text parameters are x and y, respectively, and the text to be displayed. Therefore, the call 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'gender') plt. ylabel (u'number') plt. title (u "gender ratio analysis") plt. xticks (0, 1), (u 'male', u 'female ') rect = plt. bar (left = (0.5), height = (1, 0.35), width =, align = "center") plt. legend (rect,), (u "legend",) autolabel (rect) plt. show ()

This graph is basically complete, but you can see that a rectangle is close to the top, not very nice. It is better to leave a distance out. No specific attributes are found for this setting. However, I still use a small trick. 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 he is doing. However, when I set this value very small, the blank above will be automatically blank.

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

Whether the left and right sides can be blank is not found yet (xerr parameter is not supported)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.