Python Drawing and visualization

Source: Internet
Author: User
Tags cos ord jupyter notebook install matplotlib

Python has a lot of visualization tools, this article only describes matplotlib.

Matplotlib is a 2D drawing library that supports hard-copy and cross-system interactions that can be used in Python scripts, Ipython interactive environments, and Web applications. The project was launched by John Hunter in 2002 to build a MATLAB-style drawing interface for Python. If you use a GUI toolkit (such as Ipython) together, Matplotlib also has interactive features such as zoom and pan. It not only supports many different GUI backend on various operating systems, but also can export images to various common food consumption (vectors) and raster (raster) Graphs: PDF, SVG, JPG, PNG, BMP, GIF, etc.

Matplotlib Package

The so-called "a picture wins thousands of words", we need to visually view, analyze the data, although there are some drawing operations in pandas, but compared to the matplotlib in the drawing display more excellent results. Python provides a convenient interface for matplotlib, and we can operate on matplotlib with Pyplot, and in most cases pyplot commands are somewhat similar to MATLAB.

Import the Matplotlib package for a simple operation (you need to install PIP install matplotlib here):

import Matplotlib.pyplot as Plt# conventional notation plt# first defines two functions (sine & cosine)  Import  numpy as NpX=np.linspace (-np.pi,np.pi,256,endpoint=true)#-πto+π 256 values c,s= Np.cos (x), Np.sin (x) plt.plot (x,c) plt.plot (x,s) # this sentence is needed in Ipython's interactive environment to show it Plt.show ()

Output Result:

Basic schema of the drawing command and its property settings

As we can see from the above example, almost all of the properties and drawing frames We use are default settings. Now let's see what the basic frame of the Pyplot drawing is, and everyone who has used Photoshop knows that when drawing a canvas, the canvas here is a figure, and then the other footage is "drawn" to the graph.

1) Create a child plot on the figure and set the properties

X=np.linspace (0,10,1000)#x-axis dataY1=np.sin (x)#y-Axis dataY2=np.cos (x**2)#y-axis data x**2 that is the square of xplt.figure (figsize= (8,4)) Plt.plot (X,y1,label="$sin (x) $", color="Red", linewidth=2)#render a $ surrounded content as a mathematical formulaPlt.plot (X,y2,"b--", label="$cos (x^2) $")#specifies the color and linearity of the curve, such as ' b--' for Blue dashed lines (b: Blue,-: Dashed)Plt.xlabel ("Time (s)") Plt.ylabel ("Volt") Plt.title ("Pyplot First Example")" "Use the keyword parameter to specify the various properties of the curve you are drawing: Label: Assigns a label name to the curve, which is displayed in the icon. If the label string has a character ' $ ' before and after it, Matplotlib uses its inner latex engine to display it as a mathematical formula color: Specifies the colors of the curve.       Colors can be used to represent English words with a ' # ' character beginning with 3 16 decimal digits, such as ' #ff0000 ' indicates red. The RGB representation of 0~1, such as (1.0,0.0,0.0) also represents red. LineWidth: Specifies the width of the permission, either not an integer, or using the abbreviated parameter name LW. " "Plt.ylim (-1.5,1.5) plt.legend ()#show the legend in the lower left cornerplt.show ()

2) Create multiple sub-plot on figure

If you need to draw multiple charts, you can pass an integer argument to the figure to specify the chart ordinal, and if the drawing object of the specified ordinal already exists, the new object will not be created, but only make it the current drawing object.

Fig1=plt.figure (2) Plt.subplot (211)#subplot (211) Divide the drawing area into 2 rows * * A total of two regions, Then create an Axis object in zone 1 (upper area) Plt.subplot (212)# creates an axis object in Region 2 (lower area) plt.show ()

Output Result:

We can also split these blocks again by command (equivalent to split cell operations in Word)

F1=plt.figure (5)# Popup dialog when the caption is displayed if the form is pop-up dialog box plt.subplot (221) Plt.subplot (222) Plt.subplot (212) Plt.subplots_adjust (left =0.08,right=0.95,wspace=0.25,hspace=0.45)#  subplots_adjust operation is similar to the page CSS formatting in the margin processing, the left how much distance?  #  What's the right distance? It depends on the size you need to draw and the spacing between each module plt.show ()

Output Result:

3) Set the properties of the current object plot via axes

The above we do is to draw patterns on the figure, but when we draw too many patterns, but also need to select different small modules for formatting settings, the Axes object can be a good solution to this problem.

Fig,axes=plt.subplots (nrows=2,ncols=2)# set a 2*2 plotplt.show ()

Output Result:

Now we need to manipulate each plot (subplot) by command, set their title and delete the horizontal ordinate values.

Fig,axes=plt.subplots (nrows=2,ncols=2)#to set a 2*2 plotAxes[0,0].set (title='Upper Left') Axes[0,1].set (title='Upper Right') axes[1,0].set (title='Lower Left') axes[1,1].set (title='Lower Right')#traverse through the flat property of axes forAxinchAxes.flat:#Xticks and Yticks are set to emptyAx.set (xticks=[],yticks=[]) plt.show ()

Output Result:

In addition, the underlying operation of the plot operation is, in fact, the operation of the axes object, except that if we do not use axes and plot, it defaults to Plot.subplot (111), which means that plot is a special case of axes.

4) Save the Figure object

The last thing we do is save, the purpose of our drawing is to use it in other studies, or we want to save the results of the study, at which time we need the action to save.

Plt.savefig (R"C:\Users\123\Desktop\save_test.png", dpi=520)# default pixel dpi is 80 

It is obvious that the higher the pixels you save, the larger the memory. Only the Savefig attribute is used here to save the figure.

In addition, in addition to the above basic operations, Matplotlib also has other drawing advantages, here is just a brief introduction of its in the drawing of the things to note, more property settings please refer to: https://matplotlib.org/api/

Seaborn Module Introduction

Before we briefly introduced the Matplotlib Library's drawing function and the property setting, for the general drawing, uses the Pandas drawing function to be sufficient, but if has the thorough research to the Matplotlib's API attribute, almost has not solved the question. But Matplotlib still has its shortcomings, matplotlib automation is very high, but it is very difficult to master how to set up the system to get an attractive figure. To control the appearance of the matplotlib chart, the Seaborn module comes with many custom themes and advanced interfaces.

1) The effect of not adding Seaborn module

 import   NumPy as NP  import   matplotlib as MPL  import   Matplotlib.pyplot as pltnp.random.seed (sum (Map (ord,  "  aesthetics   "  #   First define a function to draw a sine function, Helps you understand the different style parameters you can control  def  sinplot (flip=1 =np.linspace (0,14,100 for  i in  range (1,7 +i*0.5) * (7-i) *flip) Sinplot () plt.show ()  

Output Result:

2) Effect of adding Seaborn module

ImportNumPy as NPImportMatplotlib as MplImportMatplotlib.pyplot as Plt#added the Seaborn modulenp.random.seed (SUM (Map (ORD,"Aesthetics")))#first define a function to draw a sine function to help you understand the different style parameters that can be controlleddefSinplot (flip=1): x=np.linspace (0,14,100)     forIinchRange (1,7): Plt.plot (X,np.sin (x+i*0.5) * (7-i) *Flip)#Convert to Seaborn module, only need to introduce Seaborn moduleImportSeaborn as SNS#Add Seaborn ModuleSinplot () plt.show ( )

Output effect:

The Jupyter notebook editor used in small series is not significantly different from the effects of using Seaborn modules.

The advantages of using Seaborn are:

    1. Seaborn The default light gray background and white grid lines are inspired by matplotlib, but are softer than the matplotlib color
    2. Seaborn set the drawing style parameters and data parameters separately.

Seaborn has two sets of functions that control the style: the Axes_style ()/set_style () function and the Plotting_context ()/set_context () function.

The Axes_style () function and the Plotting_context () function return the parameter dictionary, the Set_style () function, and the Set_context () function to set matplotlib.

Use the Set_style () function

Import Seaborn as SNS " " Seaborn has 5 predefined themes: Darkgrid (Gray background + white grid) Whitegrid (white background + black mesh) Dark (gray background only) white (only with the whites background) ticks (axis with scale) The default theme is Darkgrid, Modify the theme to use the Set_style function 'sns.set_style ("whitegrid") Sinplot ( ) #即上段代码中定义的函数plt. Show ()

Output Result:

Use the Set_context () function

" " context to set the size size of the output picture (scale) There are 4 predefined contexts in Seaborn: paper, notebook, talk, and poster use notebook context by default " " Sns.set_context ("poster") Sinplot () # the function plt.show () as defined in the preceding article

Output Result:

Use Seaborn to "play cool"

However, Seaborn can be used not only to change the background color, or to change the canvas

Python Drawing and visualization

Related Article

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.