程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python data visualization series tutorial -- complete solution of Matplotlib drawing

編輯:Python

Hello everyone , I meet you again , I'm your friend, Quan Jun .


Full stack engineer development manual ( author : Luan Peng ) python The whole course

matplotlib Is subject to MATLAB Inspired by .MATLAB yes data Languages and tools widely used in the field of graphics .MATLAB Languages are process-oriented . Using function calls ,MATLAB You can easily use one line of command to draw a straight line , Then adjust the result with a series of functions .

matplotlib There is a complete imitation MATLAB Drawing interface in the form of function , stay matplotlib.pyplot Module . This set of function interfaces is convenient MATLAB User transition to matplotlib package

 import matplotlib.pyplot as plt

In the drawing structure ,figure create a window ,subplot Create subgraphs . All painting can only be done on subgraphs .plt Represents the current subgraph , If not, create a subgraph . So you'll see some tutorials using plt Set it up , Some tutorials use subgraph properties to set . They often have corresponding function .

Configuration parameters :

axex: Set the color of the axis boundary and surface 、 Coordinate scale value size and grid display figure: control dpi、 Border colors 、 Figure size 、 And subareas ( subplot) Set up font: Font set (font family)、 Font size and style settings grid: Set grid color and linearity legend: Set the display of the legend and the text in it line: Set the line ( Color 、 Linetype 、 Width etc. ) And tags patch: It's filling 2D Graphic objects of space , Like polygons and circles . Control line width 、 Color and anti aliasing settings, etc . savefig: You can set the saved graphics separately . for example , Set the background of the rendered file to white . verbose: Set up matplotlib Information output during execution , Such as silent、helpful、debug and debug-annoying. xticks and yticks: by x,y Set the color of the major and minor scales of the axis 、 size 、 Direction , And label size .

Line related attribute tag settings

 Line style linestyle or ls describe
‘-‘ Solid line
‘:’ Dotted line
‘–’ Broken line
‘None’,’ ‘,’’ Draw nothing
‘-.’ Point line 

Line marking

 Mark maker describe
‘o’ circle
‘.’ spot
‘D’ The diamond
‘s’ Square
‘h’ hexagon 1
‘*’ asterisk
‘H’ hexagon 2
‘d’ Little diamond
‘_’ Level
‘v’ A triangle with a corner down
‘8’ Octagon
‘<’ A triangle with one corner to the left
‘p’ pentagon
‘>’ A triangle with one corner to the right
‘,’ Pixels
‘^’ A triangle with a corner up
‘+’ plus
‘\ ‘ A vertical bar
‘None’,’’,’ ‘ nothing
‘x’ X

Color

 Alias Color
b Blue
g green
r Red
y yellow
c Cyan
k black
m Magenta
w white 

If these two colors are not enough , There are two other ways to define color values :

1、 Use HTML Hexadecimal string color=‘#123456’ Use legal HTML Color name (’red’,’chartreuse’ etc. ). 2、 You can also pass in a normalization to [0,1] Of RGB Yuan Zu . color=(0.3,0.3,0.4)

Background color

Through Xiang Ru matplotlib.pyplot.axes() perhaps matplotlib.pyplot.subplot() Such a method provides a axisbg Parameters , You can specify the background color of the coordinates .

subplot(111,axisbg=(0.1843,0.3098,0.3098))

The following examples include

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

Drawing operation steps ( Point graph 、 For example, a line chart )

# Use numpy Generate data
x=np.arange(-5,5,0.1)
y=x*3
# create a window 、 Subgraphs
# Method 1: Create a window first , Create a new sub map .( Make sure to draw )
fig = plt.figure(num=1, figsize=(15, 8),dpi=80) # Open a window , Set the size at the same time , The resolution of the
ax1 = fig.add_subplot(2,1,1) # adopt fig Add subgraph , Parameters : Row number , Number of columns , Number one .
ax2 = fig.add_subplot(2,1,2) # adopt fig Add subgraph , Parameters : Row number , Number of columns , Number one .
print(fig,ax1,ax2)
# Method 2: Create windows and multiple subgraphs at once .( Blank is not drawn )
fig,axarr = plt.subplots(4,1) # Open a new window , And add 4 Subtext , Returns an array of subgraphs
ax1 = axarr[0] # Get a subgraph from the subgraph array
print(fig,ax1)
# Method 3: Create a window and a sub graph at once .( Blank is not drawn )
ax1 = plt.subplot(1,1,1,facecolor='white') # Open a new window , establish 1 Subtext .facecolor Set the background color
print(ax1)
# Get a reference to the window , Apply to the above three methods
# fig = plt.gcf() # Get the current figure
# fig=ax1.figure # Gets the window to which the specified sub graph belongs
# fig.subplots_adjust(left=0) # Set the left inner margin of the window to 0, That is to say, leave the left blank for 0.
# Set up the basic elements of the subgraph
ax1.set_title('python-drawing') # Set up the body ,plt.title
ax1.set_xlabel('x-name') # Set up x Axis name ,plt.xlabel
ax1.set_ylabel('y-name') # Set up y Axis name ,plt.ylabel
plt.axis([-6,6,-10,10]) # Set the horizontal and vertical axis range , This is broken down into the following two functions in the subgraph
ax1.set_xlim(-5,5) # Set the horizontal axis range , Will cover the abscissa above ,plt.xlim
ax1.set_ylim(-10,10) # Set the vertical axis range , Will override the ordinates above ,plt.ylim
xmajorLocator = MultipleLocator(2) # Define the scale difference of the horizontal major scale label as 2 Multiple . It's just a few ticks apart to show a label text
ymajorLocator = MultipleLocator(3) # Define the scale difference of the vertical major scale label as 3 Multiple . It's just a few ticks apart to show a label text
ax1.xaxis.set_major_locator(xmajorLocator) #x Axis Apply the defined horizontal major scale format . If not applied, the default scale format will be used
ax1.yaxis.set_major_locator(ymajorLocator) #y Axis Apply the defined vertical major scale format . If not applied, the default scale format will be used
ax1.xaxis.grid(True, which='major') #x The grid of the axis uses the defined major scale format
ax1.yaxis.grid(True, which='major') #x The grid of the axis uses the defined major scale format
ax1.set_xticks([]) # Remove axis scale
ax1.set_xticks((-5,-3,-1,1,3,5)) # Set axis scale
ax1.set_xticklabels(labels=['x1','x2','x3','x4','x5'],rotation=-30,fontsize='small') # Set the display text of the scale ,rotation Rotation Angle ,fontsize font size
plot1=ax1.plot(x,y,marker='o',color='g',label='legend1') # Point graph :marker Icon
plot2=ax1.plot(x,y,linestyle='--',alpha=0.5,color='r',label='legend2') # Line graph :linestyle linear ,alpha transparency ,color Color ,label Legend text
ax1.legend(loc='upper left') # Show Legend ,plt.legend()
ax1.text(2.8, 7, r'y=3*x') # Display text at specified location ,plt.text()
ax1.annotate('important point', xy=(2, 6), xytext=(3, 1.5), # Add labels , Parameters : Annotated text 、 Point of reference 、 Text location 、 Arrow properties
arrowprops=dict(facecolor='black', shrink=0.05),
)
# Show grid .which The value of the parameter is major( Just draw the big scale )、minor( Just draw small scales )、both, The default value is major.axis by 'x','y','both'
ax1.grid(b=True,which='major',axis='both',alpha= 0.5,color='skyblue',linestyle='--',linewidth=2)
axes1 = plt.axes([.2, .3, .1, .1], facecolor='y') # Add a sub graph to the current window ,rect=[ Left , Next , wide , high ], Is the absolute layout used , Don't occupy space with existing windows
axes1.plot(x,y) # Draw a picture on the sub picture
plt.savefig('aa.jpg',dpi=400,bbox_inches='tight') #savefig Save the picture ,dpi The resolution of the ,bbox_inches The size of the white space around the subgraph
plt.show() # open windows , For the method 1 Create sure to draw in the window , For the method 2 Method 3 Created window , If the coordinate system is all blank , No drawing 

plot The properties that can be set during include the following :

 attribute Value type
alpha Floating point value
animated [True / False]
antialiased or aa [True / False]
clip_box matplotlib.transform.Bbox example
clip_on [True / False]
clip_path Path example , Transform, as well as Patch example
color or c whatever matplotlib Color
contains Hit test function
dash_capstyle ['butt' / 'round' / 'projecting']
dash_joinstyle ['miter' / 'round' / 'bevel']
dashes Connection in points / Disconnect the ink sequence
data (np.array xdata, np.array ydata)
figure matplotlib.figure.Figure example
label Any string
linestyle or ls [ '-' / '--' / '-.' / ':' / 'steps' / ...]
linewidth or lw Floating point value in points
lod [True / False]
marker [ '+' / ',' / '.' / '1' / '2' / '3' / '4' ]
markeredgecolor or mec whatever matplotlib Color
markeredgewidth or mew Floating point value in points
markerfacecolor or mfc whatever matplotlib Color
markersize or ms Floating point value
markevery [ None / An integer value / (startind, stride) ]
picker For interactive line selection
pickradius Pick and select the radius of the line
solid_capstyle ['butt' / 'round' / 'projecting']
solid_joinstyle ['miter' / 'round' / 'bevel']
transform matplotlib.transforms.Transform example
visible [True / False]
xdata np.array
ydata np.array
zorder Any number 

One window, many pictures

# A window , More than one picture , Multiple data
sub1=plt.subplot(211,facecolor=(0.1843,0.3098,0.3098)) # Divide the window into 2 That's ok 1 Column , In the 1 Make a picture , And set the background color
sub2=plt.subplot(212) # Divide the window into 2 That's ok 1 Column , In the 2 Make a picture
sub1.plot(x,y) # Draw a subgraph
sub2.plot(x,y) # Draw a subgraph
axes1 = plt.axes([.2, .3, .1, .1], facecolor='y') # Add a sub coordinate system ,rect=[ Left , Next , wide , high ]
plt.plot(x,y) # Draw the sub coordinate system ,
axes2 = plt.axes([0.7, .2, .1, .1], facecolor='y') # Add a sub coordinate system ,rect=[ Left , Next , wide , high ]
plt.plot(x,y)
plt.show()

Polar coordinates

Attribute setting same point graph 、 In the line diagram .

fig = plt.figure(2) # Open a new window
ax1 = fig.add_subplot(1,2,1,polar=True) # Start a polar subgraph
theta=np.arange(0,2*np.pi,0.02) # Angle series value
ax1.plot(theta,2*np.ones_like(theta),lw=2) # drawing , Parameters : angle , radius ,lw Line width
ax1.plot(theta,theta/6,linestyle='--',lw=2) # drawing , Parameters : angle , radius ,linestyle style ,lw Line width
ax2 = fig.add_subplot(1,2,2,polar=True) # Start a polar subgraph
ax2.plot(theta,np.cos(5*theta),linestyle='--',lw=2)
ax2.plot(theta,2*np.cos(4*theta),lw=2)
ax2.set_rgrids(np.arange(0.2,2,0.2),angle=45) # Distance from grid axis , Axis scale and display position
ax2.set_thetagrids([0,45,90]) # Angle grid axis , Range 0-360 degree
plt.show()

Bar charts

Attribute setting same point graph 、 In the line diagram .

plt.figure(3)
x_index = np.arange(5) # The index of the column
x_data = ('A', 'B', 'C', 'D', 'E')
y1_data = (20, 35, 30, 35, 27)
y2_data = (25, 32, 34, 20, 25)
bar_width = 0.35 # Define a number to represent the width of each individual column
rects1 = plt.bar(x_index, y1_data, width=bar_width,alpha=0.4, color='b',label='legend1') # Parameters : Left offset 、 Height 、 Column width 、 transparency 、 Color 、 legend
rects2 = plt.bar(x_index + bar_width, y2_data, width=bar_width,alpha=0.5,color='r',label='legend2') # Parameters : Left offset 、 Height 、 Column width 、 transparency 、 Color 、 legend
# About left offset , Don't worry about the centrality of each column , Because just set the scale line in the middle of the column
plt.xticks(x_index + bar_width/2, x_data) #x Axis scale mark
plt.legend() # Show Legend
plt.tight_layout() # Automatically control the outer edge of the image , This method can not control the space between images very well
plt.show()

Histogram

fig,(ax0,ax1) = plt.subplots(nrows=2,figsize=(9,6)) # Add... To the window 2 Subtext
sigma = 1 # Standard deviation
mean = 0 # mean value
x=mean+sigma*np.random.randn(10000) # Normal distribution random number
ax0.hist(x,bins=40,normed=False,histtype='bar',facecolor='yellowgreen',alpha=0.75) #normed Is it normalized ,histtype Histogram Type ,facecolor Color ,alpha transparency
ax1.hist(x,bins=20,normed=1,histtype='bar',facecolor='pink',alpha=0.75,cumulative=True,rwidth=0.8) #bins The number of pillars ,cumulative Whether to calculate the cumulative distribution ,rwidth Column width
plt.show() # All windows run 

Scatter plot

fig = plt.figure(4) # Add a window
ax =fig.add_subplot(1,1,1) # Add a subgraph to the window
x=np.random.random(100) # Generate random arrays
y=np.random.random(100) # Generate random arrays
ax.scatter(x,y,s=x*1000,c='y',marker=(5,1),alpha=0.5,lw=2,facecolors='none') #x Abscissa ,y Ordinate ,s Image size ,c Color ,marker picture ,lw Image border width
plt.show() # All windows run 

Three dimensional diagram

fig = plt.figure(5)
ax=fig.add_subplot(1,1,1,projection='3d') # 3d drawing
x,y=np.mgrid[-2:2:20j,-2:2:20j] # obtain x Axis data ,y Axis data
z=x*np.exp(-x**2-y**2) # obtain z Axis data
ax.plot_surface(x,y,z,rstride=2,cstride=1,cmap=plt.cm.coolwarm,alpha=0.8) # Draw a three-dimensional surface
ax.set_xlabel('x-name') #x Axis name
ax.set_ylabel('y-name') #y Axis name
ax.set_zlabel('z-name') #z Axis name
plt.show()

Draw a rectangular 、 polygon 、 Circles and ellipses

fig = plt.figure(6) # Create a window
ax=fig.add_subplot(1,1,1) # Add a subgraph
rect1 = plt.Rectangle((0.1,0.2),0.2,0.3,color='r') # Create a rectangle , Parameters :(x,y),width,height
circ1 = plt.Circle((0.7,0.2),0.15,color='r',alpha=0.3) # Create an ellipse , Parameters : Center point , radius , By default, this circle will be compressed in length and width according to the window size
pgon1 = plt.Polygon([[0.45,0.45],[0.65,0.6],[0.2,0.6]]) # Create a polygon , Parameters : Coordinates of each vertex
ax.add_patch(rect1) # Add shapes to the subgraph
ax.add_patch(circ1) # Add shapes to the subgraph
ax.add_patch(pgon1) # Add shapes to the subgraph
fig.canvas.draw() # Subgraph drawing
plt.show()

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/148251.html Link to the original text :https://javaforall.cn


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved