matplotlib畫圖實例:pyplot、pylab模塊及做圖參數

http://blog.csdn.net/pipisorry/article/details/40005163html

Matplotlib.pyplot畫圖實例

{使用pyplot模塊}
python

matplotlib繪製直線、條形/矩形區域

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(-1, 2, .01)
s = np.sin(2 * np.pi * t)

plt.plot(t,s)
# draw a thick red hline at y=0 that spans the xrange
l = plt.axhline(linewidth=4, color='r')
plt.axis([-1, 2, -1, 2])
plt.show()
plt.close()

# draw a default hline at y=1 that spans the xrange
plt.plot(t,s)
l = plt.axhline(y=1, color='b')
plt.axis([-1, 2, -1, 2])
plt.show()
plt.close()

# draw a thick blue vline at x=0 that spans the upper quadrant of the yrange
plt.plot(t,s)
l = plt.axvline(x=0, ymin=0, linewidth=4, color='b')
plt.axis([-1, 2, -1, 2])
plt.show()
plt.close()

# draw a default hline at y=.5 that spans the the middle half of the axes
plt.plot(t,s)
l = plt.axhline(y=.5, xmin=0.25, xmax=0.75)
plt.axis([-1, 2, -1, 2])
plt.show()
plt.close()

plt.plot(t,s)
p = plt.axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)
p = plt.axvspan(1.25, 1.55, facecolor='g', alpha=0.5)
plt.axis([-1, 2, -1, 2])
plt.show()
效果圖展現

Note: 設置直線相應位置的值顯示:plt.text(max_x, 0, str(round(max_x, 2)))。也就是直接在指定座標寫文字。不知道有沒有其餘方法?linux

[matplotlib.pyplot.axhline]git

另外一種繪製直線的方式github

plt.hlines(hline, xmin=plt.gca().get_xlim()[0], xmax=plt.gca().get_xlim()[1], linestyles=line_style, colors=color)


直方圖

plt.hist(songs_plays, bins=50,range=(0, 50000), color='lightblue',normed=True)

Note: normed是將y座標按比例畫圖,而不是數目。canvas


hist轉換成plot折線圖

plt.hist直接繪製數據是hist圖api

plt.hist(z, bins=500, normed=True)
hist圖轉換成折線圖
cnts, bins = np.histogram(z, bins=500, normed=True)
bins = (bins[:-1] + bins[1:]) / 2
plt.plot(bins, cnts)

[ numpy教程 - 統計函數:histogram]


散點圖、梯形圖、柱狀圖、填充圖

散列圖scatter()

使用plot()畫圖時。假設指定樣式參數爲僅繪製數據點,那麼所繪製的就是一幅散列圖。但是這樣的方法所繪製的點沒法單獨指定顏色和大小。
scatter()所繪製的散列圖卻可以指定每個點的顏色和大小。數組


scatter()的前兩個參數是數組,分別指定每個點的X軸和Y軸的座標。
s參數指定點的大 小。值和點的面積成正比。它可以是一個數,指定所有點的大小;也可以是數組。分別對每個點指定大小。dom


c參數指定每個點的顏色。可以是數值或數組。這裏使用一維數組爲每個點指定了一個數值。ide

經過顏色映射表,每個數值都會與一個顏色相相應。

默認的顏色映射表中藍色與最小值相應,紅色與最大值相應。當c參數是形狀爲(N,3)或(N,4)的二維數組時。則直接表示每個點的RGB顏色。
marker參數設置點的形狀,可以是個表示形狀的字符串,也可以是表示多邊形的兩個元素的元組。第一個元素表示多邊形的邊數。第二個元素表示多邊形的樣式,取值範圍爲0、一、二、3。0表示多邊形,1表示星形,2表示放射形。3表示忽略邊數而顯示爲圓形。


alpha參數設置點的透明度。
lw參數設置線寬,lw是line width的縮寫。
facecolors參數爲「none」時,表示散列點沒有填充色。


柱狀圖bar()

用每根柱子的長度表示值的大小,它們通常用來比較兩組或多組值。
bar()的第一個參數爲每根柱子左邊緣的橫座標;第二個參數爲每根柱子的高度;第三個參數指定所有柱子的寬度,當第三個參數爲序列時,可以爲每根柱子指定寬度。bar()不本身主動改動顏色。


n = np.array([0,1,2,3,4,5])
x = np.linspace(-0.75, 1., 100)

fig, axes = plt.subplots(1, 4, figsize=(12,3))

axes[0].scatter(x, x + 0.25*np.random.randn(len(x)))

axes[1].step(n, n**2, lw=2)

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)

axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);

Note: axes子圖設置title: axes.set_title("bar plot")


散點圖(改變顏色,大小)

 
  

import numpy as np import matplotlib.pyplot as plt

 
  

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
color = 2 * np.pi * np.random.rand(N)
plt.scatter(x, y, s=area, c=color, alpha=0.5, cmap=plt.cm.hsv)
plt.show()

matplotlib繪製散點圖給點加上凝視

plt.scatter(data_arr[:, 0], data_arr[:, 1], c=class_labels)
for i, class_label in enumerate(class_labels):
    plt.annotate(class_label, (data_arr[:, 0][i], data_arr[:, 1][i]))
[ matplotlib scatter plot with different text at each data point]

[matplotlib.pyplot.scatter]

對數座標圖

plot()所繪製圖表的X-Y軸座標都是算術座標。
繪製對數座標圖的函數有三個:semilogx()、semilogy()和loglog(),它們分別繪製X軸爲對數座標、Y軸爲對數座標以及兩個軸都爲對數座標時的圖表。


如下的程序使用4種不一樣的座標系繪製低通濾波器的頻率響應曲線。
當中,左上圖爲plot()繪製的算術座標系。右上圖爲semilogx()繪製的X軸對數座標系,左下圖 爲semilogy()繪製的Y軸對數座標系。右下圖爲loglog()繪製的雙對數座標系。使用雙對數座標系表示的頻率響應曲線一般被稱爲波特圖。
import numpy as np
import matplotlib.pyplot as plt

w = np.linspace(0.1, 1000, 1000)
p = np.abs(1/(1+0.1j*w)) # 計算低通濾波器的頻率響應
plt.subplot(221)
plt.plot(w, p, linewidth=2)
plt.ylim(0,1.5)

plt.subplot(222)
plt.semilogx(w, p, linewidth=2)
plt.ylim(0,1.5)

plt.subplot(223)
plt.semilogy(w, p, linewidth=2)
plt.ylim(0,1.5)

plt.subplot(224)
plt.loglog(w, p, linewidth=2)
plt.ylim(0,1.5)

plt.show()

極座標圖

極座標系是和笛卡爾(X-Y)座標系全然不一樣的座標系,極座標系中的點由一個夾角和一段相對中心點的距離來表示。polar(theta, r, **kwargs)
可以polar()直接建立極座標子圖並在當中繪製曲線。也可以使用程序中調用subplot()建立子圖時經過設 polar參數爲True,建立一個極座標子圖,而後調用plot()在極座標子圖中畫圖。

演示樣例1

fig = plt.figure()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = linspace(0, 2 * pi, 100)
ax.plot(t, t, color='blue', lw=3);

演示樣例2

import numpy as np
import matplotlib.pyplot as plt

theta = np.arange(0, 2*np.pi, 0.02)
plt.subplot(121, polar=True)
plt.plot(theta, 1.6*np.ones_like(theta), linewidth=2) #繪製同心圓
plt.plot(3*theta, theta/3, "--", linewidth=2)

plt.subplot(122, polar=True)
plt.plot(theta, 1.4*np.cos(5*theta), "--", linewidth=2)
plt.plot(theta, 1.8*np.cos(4*theta), linewidth=2)
plt.rgrids(np.arange(0.5, 2, 0.5), angle=45)
plt.thetagrids([0, 45])

plt.show()
Note:rgrids()設置同心圓柵格的半徑大小和文字標註的角度。所以右圖中的虛線圓圈有三個。 半徑分別爲0.五、1.0和1.5,這些文字沿着45°線排列。
Thetagrids()設置放射線柵格的角度, 所以右圖中僅僅有兩條放射線,角度分別爲0°和45°。

[matplotlib.pyplot.polar(*args, **kwargs)]

等值線圖

使用等值線圖表示二元函數z=f(x,y)

所謂等值線,是指由函數值相等的各點連成的平滑曲線。等值線可以直觀地表示二元函數值的變化趨勢,好比等值線密集的地方表示函數值在此處的變化較大。


matplotlib中可以使用contour()和contourf()描繪等值線,它們的差異是:contourf()所獲得的是帶填充效果的等值線。


import numpy as np
import matplotlib.pyplot as plt

y, x = np.ogrid[-2:2:200j, -3:3:300j]
z = x * np.exp( - x**2 - y**2)

extent = [np.min(x), np.max(x), np.min(y), np.max(y)]

plt.figure(figsize=(10,4))
plt.subplot(121)
cs = plt.contour(z, 10, extent=extent)
plt.clabel(cs)
plt.subplot(122)
plt.contourf(x.reshape(-1), y.reshape(-1), z, 20)
plt.show()
爲了更淸楚地區分X軸和Y軸。這裏讓它們的取值範圍和等分次數均不相同.這樣得 到的數組z的形狀爲(200, 300),它的第0軸相應Y軸、第1軸相應X軸。
調用contour()繪製數組z的等值線圖,第二個參數爲10,表示將整個函數的取值範圍等分爲10個區間,即顯示的等值線圖中將有9條等值線。可以使用extent參數指定等值線圖的X軸和Y軸的數據範圍。


contour()所返回的是一個QuadContourSet對象, 將它傳遞給clabel(),爲當中的等值線標上相應的值。
調用contourf(),繪製將取值範圍等分爲20份、帶填充效果的等值線圖。

這裏演示了第二種設置X、Y軸取值範圍的方法,它的前兩個參數各自是計算數組z時所使用的X軸和Y軸上的取樣點,這兩個數組必須是一維的。

使用等值線繪製隱函數f(x,y)=0曲線

顯然,沒法像繪製通常函數那樣,先建立一個等差數組表示變量的取值點。而後計算出數組中每個x所相應的y值。

可以使用等值線解決問題,顯然隱函數的曲線就是值等於0的那條等值線。
程序繪製函數在f(x,y)=0和 f(x,y)-0.1 = 0時的曲線。
import numpy as np
import matplotlib.pyplot as plt

y, x = np.ogrid[-1.5:1.5:200j, -1.5:1.5:200j]
f = (x**2 + y**2)**4 - (x**2 - y**2)**2
plt.figure(figsize=(9,4))
plt.subplot(121)
extent = [np.min(x), np.max(x), np.min(y), np.max(y)]
cs = plt.contour(f, extent=extent, levels=[0, 0.1], colors=["b", "r"], linestyles=["solid", "dashed"], linewidths=[2, 2])
plt.subplot(122)
for c in cs.collections:
    data = c.get_paths()[0].vertices
    plt.plot(data[:,0], data[:,1], color=c.get_color()[0], linewidth=c.get_linewidth()[0])

plt.show()

contour() levels參數指定所繪製等值線相應的函數值。這裏設置levels參數爲[0,0.1],所以終於將繪製兩條等值線。


觀察圖會發現。表示隱函數f(x)=0藍色實線並不是全然連續的。在圖的中間部分它由不少孤立的小段構成。

因爲等值線在原點附近無限靠近,所以無論對函數f的取值空間怎樣進行細分,老是會有沒法分開的地方。終於形成了圖中的那些孤立的細小區域。

而表示隱函數f(x,y)=0的紅色虛線則是閉合且連續的。

contour()返回對象QuadContourSet

可以經過contour()返回對象得到等值線上每點的數據。如下咱們在IPython中觀察變量cs,它是一個 QuadContourSet 對象:
cs對象的collections屬性是一個等值線列表,每條等值線用一個LineCollection對象表示:
>>> cs.collections
<a list of 2 collections.LineCollection objects>
每個LineCollection對象都有它本身的顏色、線型、線寬等屬性,注意這些屬性所得到的結果外面另外一層封裝,要得到其第0個元素纔是真正的配置:
>>> c0.get_color()[0]
array([ 0., 0., 1., 1.])
>>> c0.get_linewidth()[0]
2
由類名可知,LineCollection對象是一組曲線的集合。所以它可以表示像藍色實線那樣由多條線構成的等值線。它的get_paths()方法得到構成等值線的所有路徑,本例中藍色實線
所表示的等值線由42條路徑構成:
>>> len(cs.collections[0].get_paths())
42
路徑是一個Path對象,經過它的vertices屬性可以得到路徑上所有點的座標:
>>> path = cs.collections[0].get_paths()[0]
>>> type(path)
<class 'matplotlib.path.Path'>
>>> path.vertices
array([[-0.08291457, -0.98938936],
[-0.09039269, -0.98743719],
…,
[-0.08291457, -0.98938936]])
上面的程序plt.subplot(122)就是從等值線集合cs中找到表示等值線的路徑,並使用plot()將其繪製出來。

皮皮blog



Matplotlib.pylab畫圖實例

{使用pylab模塊}

matplotlib還提供了一個名爲pylab的模塊,當中包含了不少NumPy和pyplot模塊中常用的函數,方便用戶高速進行計算和畫圖,十分適合在IPython交互式環境中使用。這裏使用如下的方式加載pylab模塊:

>>> import pylab as pl
Note:import pyplot as plt也相同可以
兩種常用圖類型

Line and scatter plots(使用plot()命令), histogram(使用hist()命令)

1 折線圖&散點圖 Line and scatter plots

折線圖 Line plots(關聯一組x和y值的直線)

import numpy as np
import pylab as pl
 
x = [1, 2, 3, 4, 5]# Make an array of x values
y = [1, 4, 9, 16, 25]# Make an array of y values for each x value
 
pl.plot(x, y)# use pylab to plot x and y
pl.show()# show the plot on the screen

image

plot(x, y)        # plot x and y using default line style and color
plot(x, y, 'bo')  # plot x and y using blue circle markers
plot(y)           # plot y using x as index array 0..N-1
plot(y, 'r+')     # ditto, but with red plusses

plt.plot(ks, wssses, marker='*', markerfacecolor='r', linestyle='-', color='b')

 散點圖 Scatter plots

把pl.plot(x, y)改爲pl.plot(x, y, 'o')

image

美化 Making things look pretty

線條顏色 Changing the line color

紅色:把pl.plot(x, y, 'o')改爲pl.plot(x, y, ’or’)

線條樣式 Changing the line style

虛線:plot(x,y, '--')

marker樣式 Changing the marker style

藍色星型markers:plot(x,y, ’b*’)

詳細見附錄 - matplotlib中的做圖參數


圖和軸標題以及軸座標限度 Plot and axis titles and limits

import numpy as np
import pylab as pl
 
x = [1, 2, 3, 4, 5]# Make an array of x values
y = [1, 4, 9, 16, 25]# Make an array of y values for each x value
pl.plot(x, y)# use pylab to plot x and y
 
pl.title(’Plot of y vs. x’)# give plot a title
pl.xlabel(’x axis’)# make axis labels
pl.ylabel(’y axis’)
 
pl.xlim(0.0, 7.0)# set axis limits
pl.ylim(0.0, 30.)
 
pl.show()# show the plot on the screen

image

 一個座標系上繪製多個圖 Plotting more than one plot on the same set of axes

依次做圖就能夠

import numpy as np
import pylab as pl 
x1 = [1, 2, 3, 4, 5]# Make x, y arrays for each graph
y1 = [1, 4, 9, 16, 25]
x2 = [1, 2, 4, 6, 8]
y2 = [2, 4, 8, 12, 16]
 
pl.plot(x1, y1, ’r’)# use pylab to plot x and y
pl.plot(x2, y2, ’g’)
 
pl.title(’Plot of y vs. x’)# give plot a title
pl.xlabel(’x axis’)# make axis labels
pl.ylabel(’y axis’) 
 
pl.xlim(0.0, 9.0)# set axis limits
pl.ylim(0.0, 30.) 
 
pl.show()# show the plot on the screen

image

圖例 Figure legends

pl.legend((plot1, plot2), (’label1, label2’),loc='best’, numpoints=1)

第三個參數loc=表示圖例放置的位置:'best’‘upper right’, ‘upper left’, ‘center’, ‘lower left’, ‘lower right’.

假設在當前figure裏plot的時候已經指定了label,如plt.plot(x,z,label=" cos(x2) "),直接調用plt.legend()就可以了。

import numpy as np
import pylab as pl
 
x1 = [1, 2, 3, 4, 5]# Make x, y arrays for each graph
y1 = [1, 4, 9, 16, 25]
x2 = [1, 2, 4, 6, 8]
y2 = [2, 4, 8, 12, 16]
 
plot1 = pl.plot(x1, y1, ’r’)# use pylab to plot x and y : Give your plots names
plot2 = pl.plot(x2, y2, ’go’)
 
pl.title(’Plot of y vs. x’)# give plot a title
pl.xlabel(’x axis’)# make axis labels
pl.ylabel(’y axis’)
 
 
pl.xlim(0.0, 9.0)# set axis limits
pl.ylim(0.0, 30.)
 
 
pl.legend([plot1, plot2], (’red line’, ’green circles’), ’best’, numpoints=1)# make legend
pl.show()# show the plot on the screen

image

2 直方圖 Histograms

import numpy as np
import pylab as pl
 
# make an array of random numbers with a gaussian distribution with
# mean = 5.0
# rms = 3.0
# number of points = 1000
data = np.random.normal(5.0, 3.0, 1000)
 
# make a histogram of the data array
pl.hist(data)
 
# make plot labels
pl.xlabel(’data’)
pl.show()

假設不想要黑色輪廓可以改成pl.hist(data, histtype=’stepfilled’)

image

 

本身定義直方圖bin寬度 Setting the width of the histogram bins manually

添加兩行

bins = np.arange(-5., 16., 1.) #浮點數版本號的range
pl.hist(data, bins, histtype=’stepfilled’)

image

 

同一畫板上繪製多幅子圖 Plotting more than one axis per canvas

假設需要同一時候繪製多幅圖表的話,可以是給figure傳遞一個整數參數指定圖標的序號。假設所指定
序號的畫圖對象已經存在的話。將不建立新的對象,而僅僅是讓它成爲當前畫圖對象。

fig1 = pl.figure(1)
pl.subplot(211)
subplot(211)把畫圖區域等分爲2行*1列共兩個區域, 而後在區域1(上區域)中建立一個軸對象. pl.subplot(212)在區域2(下區域)建立一個軸對象。
image

You can play around with plotting a variety of layouts. For example, Fig. 11 is created using the following commands:

f1 = pl.figure(1)
pl.subplot(221)
pl.subplot(222)
pl.subplot(212)

image

當畫圖對象中有多個軸的時候,可以經過工具欄中的Configure Subplotsbutton,交互式地調節軸之間的間距和軸與邊框之間的距離。

假設但願在程序中調節的話,可以調用subplots_adjust函數。它有left, right, bottom, top, wspace, hspace等幾個keyword參數,這些參數的值都是0到1之間的小數。它們是以畫圖區域的寬高爲1進行正規化以後的座標或者長度。

pl.subplots_adjust(left=0.08, right=0.95, wspace=0.25, hspace=0.45)

皮皮blog



繪製圓形Circle和橢圓Ellipse

1. 調用包函數

###################################
#   coding=utf-8
#   !/usr/bin/env python
#   __author__ = 'pipi'
#   ctime 2014.10.11
#   繪製橢圓和圓形
###################################
from matplotlib.patches import Ellipse, Circle
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ell1 = Ellipse(xy = (0.0, 0.0), width = 4, height = 8, angle = 30.0, facecolor= 'yellow', alpha=0.3)
cir1 = Circle(xy = (0.0, 0.0), radius=2, alpha=0.5)
ax.add_patch(ell1)
ax.add_patch(cir1)

x, y = 0, 0
ax.plot(x, y, 'ro')

plt.axis('scaled')
# ax.set_xlim(-4, 4)
# ax.set_ylim(-4, 4)
plt.axis('equal')   #changes limits of x or y axis so that equal increments of x and y have the same length

plt.show()

參見Matplotlib.pdf Release 1.3.1文檔

 
 

p187

18.7 Ellipses (see arc)

p631class matplotlib.patches.Ellipse(xy, width, height, angle=0.0, **kwargs)Bases: matplotlib.patches.PatchA scale-free ellipse.xy center of ellipsewidth total length (diameter) of horizontal axisheight total length (diameter) of vertical axisangle rotation in degrees (anti-clockwise)p626class matplotlib.patches.Circle(xy, radius=5, **kwargs)

或者參見Matplotlib.pdf Release 1.3.1文檔contour繪製圓

#coding=utf-8
import numpy as np
import matplotlib.pyplot as plt

x = y = np.arange(-4, 4, 0.1)
x, y = np.meshgrid(x,y)
plt.contour(x, y, x**2 + y**2, [9])     #x**2 + y**2 = 9 的圓形

plt.axis('scaled')
plt.show()
p478
Axes3D. contour(X, Y, Z, *args, **kwargs)
Create a 3D contour plot.
Argument Description
X, Y, Data values as numpy.arrays
Z
extend3d
stride
zdir
offset
Whether to extend contour in 3D (default: False)
Stride (step size) for extending contour
The direction to use: x, y or z (default)
If specified plot a projection of the contour lines on this position in plane normal to zdir
The positional and other

p1025

matplotlib.pyplot.axis(*v, **kwargs)
Convenience method to get or set axis properties.

或者參見demo【pylab_examples example code: ellipse_demo.py

2. 直接繪製

#coding=utf-8
'''
Created on Jul 14, 2014
@author: pipi
'''
from math import pi
from numpy import cos, sin
from matplotlib import pyplot as plt

if __name__ == '__main__':    
    '''plot data margin'''
    angles_circle = [i*pi/180 for i in range(0,360)]                 #i先轉換成double
    #angles_circle = [i/np.pi for i in np.arange(0,360)]             # <=> 
    # angles_circle = [i/180*pi for i in np.arange(0,360)]    X
    x = cos(angles_circle)
    y = sin(angles_circle)
    plt.plot(x, y, 'r')
    
    plt.axis('equal')
    plt.axis('scaled')
    plt.show()

[http://www.zhihu.com/question/25273956/answer/30466961?

group_id=897309766#comment-61590570]

皮皮blog



畫圖小技巧

控制座標軸的顯示——使x軸顯示名稱字符串而不是數字的兩種方法

plt.xticks(range(len(list)), x, rotation='vertical')

Note:x表明一個字符串列表,如x軸上要顯示的名稱。

axes.set_xticklabels(x, rotation='horizontal', lod=True)

Note:這裏axes是plot的一個subplot()

[控制座標軸的顯示——set_xticklabels]

獲取x軸上座標最小最大值

xmin, xmax = plt.gca().get_xlim()

在指定座標寫文字

plt.text(max_x, 0, str(round(max_x, 2)))

其餘進階[matplotlib畫圖進階]

皮皮blog

from:http://blog.csdn.net/pipisorry/article/details/40005163

ref:matplotlib Plotting commands summary*

matplotlib下載及API手冊地址

Screenshots:example figures

Gallery:Click on any image to see full size image and source code

用Python作科學計算-基礎篇——matplotlib-繪製精美的圖表

Matplotlib 教程

matplotlib畫圖手冊  /subplot

matplotlib畫等高線的問題

matplotlib - 2D and 3D plotting in Python

matplotlib畫圖庫入門
繪製精美的圖表
使用 python Matplotlib 庫畫圖
barChart:http://www.cnblogs.com/qianlifeng/archive/2012/02/13/2350086.html
matplotlib--python繪製圖表 | PIL--python圖像處理

魔法(Magic)命令%magic -%matplotlibinline

Gnuplot的介紹

IBM: 基於 Python Matplotlib 模塊的高質量圖形輸出(2005年的文章有點舊)

matplotlib技巧集(繪製不連續函數的不連續點;參數曲線上繪製方向箭頭;改動缺省刻度數目。Y軸不一樣區間使用不一樣顏色填充的曲線區域。

)

Python:使用matp繪製不連續函數的不連續點。參數曲線上繪製方向箭頭。改動缺省刻度數目;Y軸不一樣區間使用不一樣顏色填充的曲線區域。

lotlib繪製圖表

matplotlib圖表中圖例大小及字體相關問題

相關文章
相關標籤/搜索