In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how to use Matplotlib. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Matplotlib is a 2D drawing library of Python language. It supports various platforms and has powerful functions. It can easily draw images of all kinds of specialties.
Operation environment
Since this is a Python language software package, you need to install the Python language environment on your machine first. At this point, please search for access methods on the Internet.
It is recommended to install through pip. The specific methods are as follows:
Sudo pip3 install matplotlib
The code in this article is tested in the following environment:
Apple OS X 10.13
Python 3.6.3
Matplotlib 2.1.1
Numpy 1.13.3
Introduction
Matplotlib is suitable for a variety of environments, including:
Python script
IPython shell
Jupyter notebook
Web application server
User graphical interface toolkit
Using Matplotlib, you can easily generate various types of images, such as histogram, spectrogram, bar chart, scatter plot and so on. Moreover, customization can be implemented very easily.
Sample starter code
Let's take a look at the simplest code example to see what Matplotlib looks like:
# test.py
Import matplotlib.pyplot as plt
Import numpy as np
Data = np.arange (100,201)
Plt.plot (data)
Plt.show ()
The body logic of this code is only three lines, but it draws a very intuitive linear graph, as shown below:
Compared with this line diagram, let's explain the logic of three lines of code:
An array of integers between [100,200] is generated by np.arange (100,201). Its value is: [100,101,102,... , 200]
Draw it through matplotlib.pyplot. Obviously, the values drawn correspond to the ordinates (y-axis) in the diagram. And matplotlib itself sets the Abscissa (x axis) of the graph for us: [0100], because we happen to have 100 values.
Display this graph through plt.show ()
This code is very simple and runs the same way. If you already have a running environment for this article, save the above code to a text file (or get the source code for this article through Github), and then you can see the above graphics on your own computer with the following command:
Python3 test.py
Note 1: in later tutorials, we will explain step by step how to customize every detail in the diagram. For example: axes, graphics, shading, line styles, and so on.
Note 2: if it is not necessary, the screenshot below will remove the border on the outside of the drawing, leaving only the main body of the drawing.
Draw more than one drawing at a time
Sometimes, we may want to draw more than one graph at a time, for example, the comparison of two sets of data, or the different presentation of a group of data, etc.
You can create multiple drawings in the following ways:
Multiple figure
Can be simply understood as a figure is a graphics window. Matplotlib.pyplot will have a default figure, or we can create more through plt.figure (). As shown in the following code:
# figure.py
Import matplotlib.pyplot as plt
Import numpy as np
Data = np.arange (100,201)
Plt.plot (data)
Data2 = np.arange (200,301)
Plt.figure ()
Plt.plot (data2)
Plt.show ()
This code draws a graph of two windows, each of which is a line graph of different intervals, as shown below:
Note: the two windows in the initial state are completely coincident.
Multiple subplot
In some cases, we want to display multiple graphics in the same window. Multiple subplot can be used at this point. Here is an example of a code:
# subplot.py
Import matplotlib.pyplot as plt
Import numpy as np
Data = np.arange (100,201)
Plt.subplot (2,1,1)
Plt.plot (data)
Data2 = np.arange (200,301)
Plt.subplot (2,1,2)
Plt.plot (data2)
Plt.show ()
In this code, we are familiar with everything except the subplot function. The first two parameters of the subplot function specify the number of subplot, that is, they split the current graph in the form of a matrix, and the two integers specify the number of rows and columns of the matrix, respectively. The third parameter refers to the index in the matrix.
Therefore, the following line of code refers to the first subplot in the two-line and one-column subplot.
Plt.subplot (2,1,1)
The following line of code refers to the second subplot in two rows and one column of subplot.
Plt.subplot (2,1,2)
So the result of this code looks like this:
The arguments to the subplot function not only support the above form, but also combine three integers (less than 10) into one integer. For example, 2, 1, 1 can be written as 211, and 1 can be written as 212.
Therefore, the result of the following code is the same:
Import matplotlib.pyplot as plt
Import numpy as np
Data = np.arange (100,201)
Plt.subplot (211)
Plt.plot (data)
Data2 = np.arange (200,301)
Plt.subplot (212)
Plt.plot (data2)
Plt.show ()
For a detailed description of the subplot function, please see here: matplotlib.pyplot.subplot
Common graphic exampl
Matplotlib can generate so many graphics styles that they are amazing. You can feel it here: Matplotlib Gallery.
In this article, as the first introductory tutorial, let's take a look at some of the most commonly used graphics.
Linear graph
In the previous example, the points on the horizontal axis of a linear graph are automatically generated, and we probably want to set it actively. In addition, we may also want to customize the lines. Take a look at the following example:
# plot.py
Import matplotlib.pyplot as plt
Plt.plot ([1,2,3], [3,6,9],'- r')
Plt.plot ([1,2,3], [2,4,9],': G')
Plt.show ()
This code allows us to get a graph like this:
The code is as follows:
The first array of the plot function is the value of the horizontal axis and the second array is the value of the vertical axis, so one of them is a straight line and the other is a broken line.
The last parameter is made up of two characters, the style and color of the line. The former is a red straight line and the latter is a green dotted line. For a description of styles and colors, see the API Doc:matplotlib.pyplot.plot of the plot function
Scatter plot
The scatter function is used to draw scatter plots. Similarly, this function requires two sets of paired data to specify the coordinates of the x and y axes. Here is an example of a code:
# scatter.py
Import matplotlib.pyplot as plt
Import numpy as np
N = 20
Plt.scatter (np.random.rand (N) * 100)
Np.random.rand (N) * 100
Cymbals, slots 100, alpha=0.5)
Plt.scatter (np.random.rand (N) * 100)
Np.random.rand (N) * 100
Cymbals, slots 200, alpha=0.5)
Plt.scatter (np.random.rand (N) * 100)
Np.random.rand (N) * 100
Cymbals, slots 300, alpha=0.5)
Plt.show ()
The code is as follows:
This picture contains three sets of data, each containing 20 random coordinates.
Parameter c represents the color of the point, s is the size of the point, and alpha is the transparency
The figure drawn by this code is as follows:
For a detailed description of the scatter function, please see here: matplotlib.pyplot.scatter
Pie chart
The pie function is used to draw a pie chart. Pie charts are usually used to express the percentage of each part of a collection.
# pie.py
Import matplotlib.pyplot as plt
Import numpy as np
Labels = ['Mon',' Tue', 'Wed',' Thu', 'Fri',' Sat', 'Sun']
Data = np.random.rand (7) * 100
Plt.pie (data, labels=labels, autopct='%1.1f%%')
Plt.axis ('equal')
Plt.legend ()
Plt.show ()
The code is as follows:
Data is a set of random values containing seven pieces of data
The label in the figure is specified by labels
Autopct specifies the precision format of the numeric value
Plt.axis ('equal') sets the axis to be the same size
Plt.legend () indicates that you want to draw the legend (see the upper right corner of the image below)
The output of this code is as follows:
For a detailed description of the pie function, please see here: matplotlib.pyplot.pie
Bar chart
The bar function is used to draw bar graphs. Bar charts are often used to describe the comparison of a set of data, such as the daily traffic flow of a city seven days a week.
The following is a code example:
# bar.py
Import matplotlib.pyplot as plt
Import numpy as np
N = 7
X = np.arange (N)
Data = np.random.randint (low=0, high=100, size=N)
Colors = np.random.rand (N * 3) .reshape (N,-1)
Labels = ['Mon',' Tue', 'Wed',' Thu', 'Fri',' Sat', 'Sun']
Plt.title ("Weekday Data")
Plt.bar (x, data, alpha=0.8, color=colors, tick_label=labels)
Plt.show ()
The code is as follows:
This picture shows a set of results containing seven random values, each of which is a random number of [0100].
Their colors are also generated by random numbers. Np.random.rand (N * 3) .reshape (N,-1) means that you make 21 (N x 3) random numbers and then assemble them into seven lines, so each line is three numbers, which corresponds to the three components of the color. If you don't understand this line of code, please learn the NumPy tutorial of Python Machine Learning Library first.
Title specifies the title of the drawing, labels specifies the label, and alpha is transparency.
The output of this code is as follows:
For a detailed description of the bar function, please see here: matplotlib.pyplot.bar
Histogram
The hist function is used to draw a histogram. A histogram looks like a bar chart. It's kind of similar. But their meanings are different, and the histogram describes the frequency of the data in a certain range of data. This is a bit abstract, which is easy to understand by describing it with a code example:
# hist.py
Import matplotlib.pyplot as plt
Import numpy as np
Data = [np.random.randint (0, n, n) for n in [3000, 4000, 5000]]
Labels = ['3K','4K','5K']
Bins = [0,100,500, 1000, 2000, 3000, 4000, 5000]
Plt.hist (data, bins=bins, label=labels)
Plt.legend ()
Plt.show ()
In the above code, [np.random.randint (0, n, n) for n in [3000, 4000, 5000]] generates an array containing three arrays, of which:
The first array contains 3000 random numbers with a range of [0, 3000)
The second array contains 4000 random numbers with a range of [0, 4000)
The third array contains 5000 random numbers with a range of [0, 5000)
The bins array is used to specify the boundaries of the histogram we display, that is, [0,100) will have a data point, [100,500) will have a data point, and so on. So the final result will show a total of seven data points. Again, we specify labels and legends.
The output of this code is shown in the following figure:
In this picture, we can see that all three sets of data have data below 3000, and the frequency is about the same. But the blue bar only has less than 3000 of the data, and the orange bar only has less than 4000 of the data. This coincides with our random array data.
Thank you for reading! This is the end of the article on "how to use Matplotlib". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.