Python基礎-畫圖:matplotlib


 

 

Python畫圖主要用到matplotlib這個庫。具體來說是pylab和pyplot這兩個子庫。這兩個庫可以滿足基本的畫圖需求。

pylab神器:pylab.rcParams.update(params)。這個函數幾乎可以調節圖的一切屬性,包括但不限於:坐標范圍,axes標簽字號大小,xtick,ytick標簽字號,圖線寬,legend字號等。

具體參數參看官方文檔:http://matplotlib.org/users/customizing.html


 

scatter和 plot 函數的不同之處

scatter才是離散點的繪制程序,plot准確來說是繪制線圖的,當然也可以畫離散點。

scatter/scatter3做散點的能力更強,因為他可以對散點進行單獨設置
所以消耗也比plot/plot3大
所以如果每個散點都是一致的時候,還是用plot/plot3好以下
如果要做一些plot沒法完成的事情那就只能用scatter了

scatter強大,但是較慢。所以如果你只是做實例中的圖,plot足夠了。


 plt.ion()用於連續顯示。

# plot the real data fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.scatter(x_data, y_data) plt.ion()#本次運行請注釋,全局運行不要注釋 plt.show()

 

首先在python中使用任何第三方庫時,都必須先將其引入。即:

import matplotlib.pyplot as plt
  • 1

或者:

from matplotlib.pyplot import *

1.建立空白圖

fig = plt.figure()

也可以指定所建立圖的大小

fig = plt.figure(figsize=(4,2))

也可以建立一個包含多個子圖的圖,使用語句:

plt.figure(figsize=(12,6)) plt.subplot(231) plt.subplot(232) plt.subplot(233) plt.subplot(234) plt.subplot(235) plt.subplot(236) plt.show()


其中subplot()函數中的三個數字,第一個表示Y軸方向的子圖個數,第二個表示X軸方向的子圖個數,第三個則表示當前要畫圖的焦點。

當然上述寫法並不是唯一的,比如我們也可以這樣寫:

fig = plt.figure(figsize=(6, 6)) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) plt.show()

plt.subplot(111)和plt.subplot(1,1,1)是等價的。意思是將區域分成1行1列,當前畫的是第一個圖(排序由行至列)。

plt.subplot(211)意思就是將區域分成2行1列,當前畫的是第一個圖(第一行,第一列)。以此類推,只要不超過10,逗號就可省去。

 

可以看到圖中的x,y軸坐標都是從0到1,當然有時候我們需要其他的坐標起始值。 
此時可以使用語句指定:

ax1.axis([-1, 1, -1, 1])

或者:

plt.axis([-1, 1, -1, 1])

效果如下:

 

2.向空白圖中添加內容,想你所想,畫你所想

首先給出一組數據:

x = [1, 2, 3, 4, 5] y = [2.3, 3.4, 1.2, 6.6, 7.0]

A.畫散點圖*

plt.scatter(x, y, color='r', marker='+') plt.show()

效果如下:

這里的參數意義:

  1. x為橫坐標向量,y為縱坐標向量,x,y的長度必須一致。
  2. 控制顏色:color為散點的顏色標志,常用color的表示如下:

    b---blue c---cyan g---green k----black m---magenta r---red w---white y----yellow

    有四種表示顏色的方式:

    • 用全名
    • 16進制,如:#FF00FF
    • 灰度強度,如:‘0.7’
  3. 控制標記風格:marker為散點的標記,標記風格有多種:

    .  Point marker , Pixel marker o Circle marker v Triangle down marker ^ Triangle up marker < Triangle left marker > Triangle right marker 1 Tripod down marker 2 Tripod up marker 3 Tripod left marker 4 Tripod right marker s Square marker p Pentagon marker * Star marker h Hexagon marker H Rotated hexagon D Diamond marker d Thin diamond marker | Vertical line (vlinesymbol) marker _ Horizontal line (hline symbol) marker + Plus marker x Cross (x) marker

B.函數圖(折線圖)

數據還是上面的。

fig = plt.figure(figsize=(12, 6)) plt.subplot(121) plt.plot(x, y, color='r', linestyle='-') plt.subplot(122) plt.plot(x, y, color='r', linestyle='--') plt.show()

效果如下: 

這里有一個新的參數linestyle,控制的是線型的格式:符號和線型之間的對應關系

- 實線 -- 短線 -. 短點相間線 : 虛點線

另外除了給出數據畫圖之外,我們也可以利用函數表達式進行畫圖,例如:y=sin(x)

from math import * from numpy import * x = arange(-math.pi, math.pi, 0.01) y = [sin(xx) for xx in x] plt.figure() plt.plot(x, y, color='r', linestyle='-.') plt.show()

效果如下:

C.扇形圖

示例:

import matplotlib.pyplot as plt y = [2.3, 3.4, 1.2, 6.6, 7.0] plt.figure() plt.pie(y) plt.title('PIE') plt.show()

效果如下:

 

D.柱狀圖bar

示例:

import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2.3, 3.4, 1.2, 6.6, 7.0] plt.figure() plt.bar(x, y) plt.title("bar") plt.show()

效果如下:

 
        

E.二維圖形(等高線,本地圖片等)

import matplotlib.pyplot as plt import numpy as np import matplotlib.image as mpimg # 2D data delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) Z = Y**2 + X**2 plt.figure(figsize=(12, 6)) plt.subplot(121) plt.contour(X, Y, Z) plt.colorbar() plt.title("contour") # read image img=mpimg.imread('marvin.jpg') plt.subplot(122) plt.imshow(img) plt.title("imshow") plt.show() #plt.savefig("matplot_sample.jpg")

效果圖:

F.對所畫圖進行補充

__author__ = 'wenbaoli' import matplotlib.pyplot as plt from math import * from numpy import * x = arange(-math.pi, math.pi, 0.01) y = [sin(xx) for xx in x] plt.figure() plt.plot(x, y, color='r', linestyle='-') plt.xlabel(u'X')#fill the meaning of X axis plt.ylabel(u'Sin(X)')#fill the meaning of Y axis plt.title(u'sin(x)')#add the title of the figure plt.show()

效果圖: 

畫網絡圖,要用到networkx這個庫,下面給出一個實例:

 
import  networkx as nx
import  pylab as plt
=  nx.Graph()
g.add_edge( 1 , 2 ,weight  =  4 )
g.add_edge( 1 , 3 ,weight  =  7 )
g.add_edge( 1 , 4 ,weight  =  8 )
g.add_edge( 1 , 5 ,weight  =  3 )
g.add_edge( 1 , 9 ,weight  =  3 )
 
g.add_edge( 1 , 6 ,weight  =  6 )
g.add_edge( 6 , 7 ,weight  =  7 )
g.add_edge( 6 , 8 ,weight  =  7
 
g.add_edge( 6 , 9 ,weight  =  6 )
g.add_edge( 9 , 10 ,weight  =  7 )
g.add_edge( 9 , 11 ,weight  =  6 )
 
 
 
fixed_pos  =  { 1 :( 1 , 1 ), 2 :( 0.7 , 2.2 ), 3 :( 0 , 1.8 ), 4 :( 1.6 , 2.3 ), 5 :( 2 , 0.8 ), 6 :( - 0.6 , - 0.6 ), 7 :( - 1.3 , 0.8 ),  8 :( - 1.5 , - 1 ),  9 :( 0.5 , - 1.5 ),  10 :( 1.7 , - 0.8 ),  11 :( 1.5 , - 2.3 )}  #set fixed layout location
 
 
 
#pos=nx.spring_layout(g) # or you can use other layout set in the module
nx.draw_networkx_nodes(g,pos  =  fixed_pos,nodelist = [ 1 , 2 , 3 , 4 , 5 ],
node_color  =  'g' ,node_size  =  600 )
nx.draw_networkx_edges(g,pos  =  fixed_pos,edgelist = [( 1 , 2 ),( 1 , 3 ),( 1 , 4 ),( 1 , 5 ),( 1 , 9 )],edge_color = 'g' ,width  =  [ 4.0 , 4.0 , 4.0 , 4.0 , 4.0 ],label  =  [ 1 , 2 , 3 , 4 , 5 ],node_size  =  600 )
 
 
nx.draw_networkx_nodes(g,pos  =  fixed_pos,nodelist = [ 6 , 7 , 8 ],
node_color  =  'r' ,node_size  =  600 )
nx.draw_networkx_edges(g,pos  =  fixed_pos,edgelist = [( 6 , 7 ),( 6 , 8 ),( 1 , 6 )],width  =  [ 4.0 , 4.0 , 4.0 ],edge_color = 'r' ,node_size  =  600 )
 
nx.draw_networkx_nodes(g,pos  =  fixed_pos,nodelist = [ 9 , 10 , 11 ],
node_color  =  'b' ,node_size  =  600 )
nx.draw_networkx_edges(g,pos  =  fixed_pos,edgelist = [( 6 , 9 ),( 9 , 10 ),( 9 , 11 )],width  =  [ 4.0 , 4.0 , 4.0 ],edge_color = 'b' ,node_size  =  600 )
 
 
plt.text(fixed_pos[ 1 ][ 0 ],fixed_pos[ 1 ][ 1 ] + 0.2 , s  =  '1' ,fontsize  =  40 )
plt.text(fixed_pos[ 2 ][ 0 ],fixed_pos[ 2 ][ 1 ] + 0.2 , s  =  '2' ,fontsize  =  40 )
plt.text(fixed_pos[ 3 ][ 0 ],fixed_pos[ 3 ][ 1 ] + 0.2 , s  =  '3' ,fontsize  =  40 )
plt.text(fixed_pos[ 4 ][ 0 ],fixed_pos[ 4 ][ 1 ] + 0.2 , s  =  '4' ,fontsize  =  40 )
plt.text(fixed_pos[ 5 ][ 0 ],fixed_pos[ 5 ][ 1 ] + 0.2 , s  =  '5' ,fontsize  =  40 )
plt.text(fixed_pos[ 6 ][ 0 ],fixed_pos[ 6 ][ 1 ] + 0.2 , s  =  '6' ,fontsize  =  40 )
plt.text(fixed_pos[ 7 ][ 0 ],fixed_pos[ 7 ][ 1 ] + 0.2 , s  =  '7' ,fontsize  =  40 )
plt.text(fixed_pos[ 8 ][ 0 ],fixed_pos[ 8 ][ 1 ] + 0.2 , s  =  '8' ,fontsize  =  40 )
plt.text(fixed_pos[ 9 ][ 0 ],fixed_pos[ 9 ][ 1 ] + 0.2 , s  =  '9' ,fontsize  =  40 )
plt.text(fixed_pos[ 10 ][ 0 ],fixed_pos[ 10 ][ 1 ] + 0.2 , s  =  '10' ,fontsize  =  40 )
plt.text(fixed_pos[ 11 ][ 0 ],fixed_pos[ 11 ][ 1 ] + 0.2 , s  =  '11' ,fontsize  =  40 )
 
 
 
plt.show()

結果如下:

 

 
        
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM