I. Recognition of the plot() function
In the use of Python for data visualization programming matplotlib library is a third-party library that we use to draw graphs on the data commonly used. It contains various types of functions, which are different types of graphs. To use the functions in the matplotlib library, you need to understand the format of the data required by the functions, which is also the focus of our study of the matplotlib library.
Direct plotting using the plot() function is for simple data in general. We can use the direct call plot () function on the list of data for direct drawing. Initial learning directly using the plot () function can facilitate our learning of the later graphics to lay the parameters of the function and the foundation.
Composition of matplotlib graphs:
- Figure (canvas)
- Axes (coordinate system)
- Axis
- Graphics ( plot(),scatter(),bar(),...)
- Title, Labels, ......
It is straightforward to use the plot() function to draw a graph such as the method below:
(x, y, fmt='xxx', linestyle=, marker=, color=, linewidth=, markersize=, label=, )
Where x,y represents the horizontal and vertical coordinates, and fmt = '#color#linestyle#marker' that represents the various parameters.
(1) linestyle: this field is the style of the line, parameter form: string
linestyle (line style)
Parameters of linestyle | linear |
'-' | solid line |
'--' | dotted line |
'-.' | dotted line |
':' | dotted dotted line |
' ' | cordless |
(2) linewidth: this parameter is the thickness of the line, the degree of thickness and the size of the set value, the parameter form: value
(3) marker: point style, string
marker (dot style)
marker | marking point |
'.' | store |
',' | pixels |
'^' 'v' '>' '<' | Upper, lower, left and right triangles |
'1' '2' '3' '4' | Upper, lower, left and right trident |
'o' | orbicular |
's' 'D' | square-shaped |
'p' | pentagon |
'h' 'H' | hexagon |
'*' | pentagram |
'+' 'x' | crossover |
'_' | horizontal coordinate line |
' | ' |
(4) markersize: the size of the point, parameter form: numeric value
(5) color: adjust the color of the line also a little bit , string, parameter form string
color (point, line color)
string (computer science) | color |
'r' | bonus |
'g' | green |
'b' | indigo plant |
'y' | pornographic |
'c' | greenish black |
'm' | character |
'k' | (loanword) hack (computing) |
'w' | stare coldly |
Here the color parameter can also have binary, decimal and other representations, while for the color, RGB is the three primary colors
(6) label: legend, legend text
Second, the basic use of plot () function
When you use plot() function, you need to import the corresponding library, after importing the library, we directly draw the picture without data, directly draw the picture will implicitly create Figure, Axes objects.
import as ()
The following simple graph is drawn by constructing the data
First the data is constructed and the parameters are set, the parameters can also be set when the data is filled into the plot() function.
# Importing packages import as plt import numpy as np # Constructed data # Position (2-dimensional: x,y one-to-one) x = (0, 2 * , 200) # 200 values from 0 to 2pi y = (x) # 200 values from sin(0) to sin(2pi) # Color (0 dimensions) c = 'red' c = 'r' c = '#FF0000' # Size (0 dimensions): line width lw = 1
draw a graph
# Generate a Figure canvas and an Axes coordinate system fig, ax = () # Drawing line graphs under the generated coordinate system (x, y, c, linewidth=lw) # Display graphics ()
Graphic presentation:
Given two sets of data, the establishment of y and x of the relationship between the trial, the use of plot function for the drawing, the drawing of the line selection point dashed line form, thickness selection 1, the point selection of the square, the point size selection of the value of 10, the legend for the '1234'
import as plt x = [1,2,3] y = [1,2,3] y = x (x,y,linestyle=':', linewidth=1, marker='d', markersize=10, label='1234') ()
Make a picture as follows.
In the following, we invoke numpy's linspace function to create a uniformly distributed sequence, and then establish a numerical relationship for x, y, from which we can create a plot.
import as plt import numpy as np x = (-100,100,10) y = x**2 + 2*x +1 (x,y,'')
to make the following pattern, it can be seen, we for the graphic settings, after we are skilled if there is no thickness of the settings can be directly reduced to a string inside the
Above is a simple graphical explanation, we are now through a simple DataFrame for data graphing, in the future data visualization we need to process the data before visualization. Here we graph through the sine and cosine functions.
#Import packages import as plt import numpy as np import pandas as pd # Use the linspace() method to compose data x = (0, 2 * , 50) # y1 = (x) y2 = (x) # Transformation of data forms df = ([x,y1,y2]).T # Rename columns = ['x','sin(x)','cos(x)'] # Data written to image, named legend (df['x'],df['sin(x)'],label='sin(x)') (df['x'],df['cos(x)'],label='cos(x)') ()
We generate data through numpy's linspace method and then through the pandas DataFrame data and then brought into the plot () function, here we need to talk about is the naming method of the legend, through the function to write the label parameter, to determine the label of the legend, and then through the legend () function to generate the legend, in the subsequent study will also be talked about! The location of the legend, the use of forms and so on.
Third, plot () function data visualization drawing as well as the basic parameters of the graph element settings
Through the drawing of the world's population change curve to understand the basic graphical parameters set, this drawing process is mainly through the population data import, understand the data structure, and then into the configuration of the drawing parameters and finally complete the production of graphics, which the basic graphical parameters used for other graphics is also applicable to learn here we only need to understand the structure of the data, constructed into the graph of the data structure to be able to draw their own desired Graphics.
First of all, data import is carried out to understand the form of data structure. In order to study the convenience of the choice of jupyter notebook for the visualization of graphical explanations.
import pandas as pd datafile = r'world_population.txt' # Open the file df = pd.read_csv(datafile) #Read the data ()#Displaying the previous part of the data
Here is the basic data style, consisting of the year and population size
Here to do the basic design of the elements, that is, for the canvas settings, before we learn the function parameters are for the middle of the graphic settings, we constitute a visual interface is through the canvas + drawing graphic styles to form a complete visual interface.
The canvas interface has settings for canvas size, canvas pixels, canvas interface, and canvas border.
import as plt # Canvas fig = (figsize=(6,4), # inches dpi=120, # dot-per-inch facecolor='#BBBBBB', frameon=True, # Canvas Borders ) (df['year'],df['population']) # Title ("1960-2009 World Population")
Composition of a complete visualization of the image in addition to the legend and the title of the image, we can set the English title through the title () method, the Chinese title to be achieved through the following code, so if we are doing the Chinese project in the package after the import can be written to set the Chinese code on the code string.
# Set Chinese fonts ['-serif'] = 'SimHei' # Set font to Simple Black (SimHei) ['-serif'] = 'FangSong' # Setting the font to FangSong(FangSong)
Of course, in addition to this relatively simple graphic we can also optimize the graphic settings, the data will be displayed more beautiful and beautiful, the graphic optimization to facilitate the presentation of the actual report is also an essential part of our current.
import as plt # Set Chinese fonts ['axes.unicode_minus'] = False # No Chinese minus sign ['-serif'] = 'FangSong' # Set the font to FangSong (Fangsong font) # Canvas fig = (figsize=(6,4), # inches dpi=120, # dot-per-inch facecolor='#BBBBBB', frameon=True, # Canvas Borders ) (df['year'],df['population'],'b:o',label='Population') # Chinese title ("1960-2009 World Population") # Font Dictionary font_dict=dict(fontsize=8, color='k', family='SimHei', weight='light', style='italic', ) # X-axis labels ("Year", loc='center', fontdict=font_dict) # loc: left center right # Y-axis labels ("Population",loc='top', fontdict=font_dict) # loc: top center bottom top center bottom # X-axis range ((2000,2010)) # Start and end of the X-axis # Y-axis range (6e9,7e9) # Start and end points of the Y-axis # X-axis scale ((2000,2011)) # X-axis scale ((6e9,7e9+1e8,1e8)) # Legend () # (labels=['population']) # Gridlines (axis='y') # axis: 'both','x','y'
The above code, the x-axis, y-axis scales, labels, fonts are defined, the legend, grid lines, etc. also made the parameters of the settings, and finally made the graphics are shown below:
summarize
to this article on the direct use of Python plot () function to draw the article is introduced to this, more related Python plot () function to draw the content of the search for my previous posts or continue to browse the following related articles I hope you will support me in the future!