Python:2D畫圖庫matplotlib學習總結


本文為學習筆記----總結!大部分為demo。一部分為學習中遇到的問題總結。包含怎么設置標簽為中文等。matlab博大精深。須要用的時候再繼續吧。

Pyplot tutorial

Demo地址為: 點擊打開鏈接 
一個簡單的樣例:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
plt.plot([1, 4, 9, 16])
plt.ylabel('some numbers')
plt.show()

執行結果為:


我僅僅指定了一組list參數。從圖中能夠看書,這組參數自己主動分配為了縱坐標。為什么會這樣呢?

你可能想知道為什么X軸的范圍是0-3。假設你提供一個單一的列表或數組的plot()命令,matplotlib假定這是一個序列的y值,並自己主動生成X值。

由於Python范圍從0開始,默認x向量從0開始並以1為步長自己主動得到X坐標。

因此X的數據為[ 0, 1, 2, 3 ]。


plot()是一種通用的命令,並將採取隨意數量的參數。默認X和Y的參數為list(實際上內部都是轉化為數組numpy)。而且長度同樣,否則報錯。


For every x, y pair of arguments, there is an optional third argument which is the format string that indicates the color and line type of the plot. The letters and symbols of the format string are from MATLAB, and you concatenate a color string with a line style string. The default format string is ‘b-‘, which is a solid blue line. For example, to plot the above with red circles, you would issue

對於每個X,Y參數對,有一個可選的第三個參數是表示顏色的和線型的格式字符串。

格式字符串的字母和符號來源於MATLAB。你能夠制定顏色和線型。

默認的格式字符串為“b-”,這是一個藍線實線。

如上圖所看到的。

plot() 文檔有完整的格式化字符串參數說明。axis() 命令指定坐標范圍[xmin, xmax, ymin, ymax]。

樣例:

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

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
結果為:



Controlling line properties

Lines have many attributes that you can set: linewidth線寬, dash style, antialiased抗鋸齒, etc; see  matplotlib.lines.Line2D . There are several ways to set line properties
1、利用keyword:
plt.plot(x, y, linewidth=2.0)
2、利用 setter方法
line1, line2 = plot(x1,y1,x2,y2)
line.set_antialiased(False) # turn off antialising
3、使用   setp()  命令
lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
Here are the available  Line2D  properties.

4、To get a list of settable line properties, call the setp() function with a line or lines as argument
比如:
lines = plt.plot([1,2,3])

plt.setp(lines)
  alpha: float
  animated: [True | False]
  antialiased or aa: [True | False]
  ...snip
以上為調用setp()第二種方法。

Working with multiple figures and axes

MATLAB, and  pyplot , have the concept of the current figure and the current axes. All plotting commands apply to the current axes. The function  gca()  returns the current axes (a matplotlib.axes.Axes  instance), and  gcf()  returns the current figure ( matplotlib.figure.Figure  instance). Normally, you don’t have to worry about this, because it is all taken care of behind the scenes. Below is a script to create two subplots.
MATLAB和pyplot,有當前圖和當前軸的概念。全部的畫圖命令適用於當前軸。

gca()方法返回當前軸(一個matplotlib.axes.axes實例)。和gcf()方法返回當前圖形(matplotlib.figure.figure實例)。通常,你不用操心這個,由於它是幕后自己主動管理的。以下是一個腳本來創建兩個圖。

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

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
結果為:

The figure() command here is optional because figure(1) will be created by default, just as a subplot(111) will be created by default if you don’t manually specify an axes. Thesubplot() command specifies numrows, numcols, fignum where fignum ranges from 1 to numrows*numcols. The commas in the subplot command are optional if numrows*numcols<10. Sosubplot(211) is identical to subplot(2,1,1). You can create an arbitrary number of subplots and axes. If you want to place an axes manually, ie, not on a rectangular grid, use theaxes() command, which allows you to specify the location as axes([left, bottom, width, height]) where all values are in fractional (0 to 1) coordinates. See pylab_examples example code: axes_demo.py for an example of placing axes manually and pylab_examples example code: line_styles.py for an example with lots-o-subplots.

You can create multiple figures by using multiple figure() calls with an increasing figure number. Of course, each figure can contain as many axes and subplots as your heart desires:

這里的figure()指令是可選的由於 figure(1)默認會被創建,就像subplot(111)將 默認創建當 你不手動指定axes的情況下。該subplot()命令指定numrows,numcols,fignum范圍從1到numrows * numcols【即211為2行1列第1幅圖。和MATLAB同樣】。

假設numrows * numcols<10,subplot()命令中的逗號是可選的。您能夠創建隨意數量的subplots和axes。假設你想手動設置一個axes,能夠使用axes()命令,它同意你指定的位置為axes([left, bottom, width, height])。全部的值都是分數(0~1)坐標。

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1,2,3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4,5,6])


plt.figure(2)                # a second figure
plt.plot([4,5,6])            # creates a subplot(111) by default

plt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1,2,3')   # subplot 211 title
plt.show()

You can clear the current figure with clf() and the current axes with cla(). If you find this statefulness, annoying, don’t despair, this is just a thin stateful wrapper around an object oriented API, which you can use instead (see Artist tutorial)

If you are making a long sequence of figures, you need to be aware of one more thing: the memory required for a figure is not completely released until the figure is explicitly closed with close(). Deleting all references to the figure, and/or using the window manager to kill the window in which the figure appears on the screen, is not enough, because pyplot maintains internal references until close() is called.

Working with text

The  text()  command can be used to add text in an arbitrary location, and the  xlabel() ylabel()  and  title()  are used to add text in the indicated locations (see  Text introduction  for a more detailed example)
加入標簽! 怎么加入中文標簽?!
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)


plt.xlabel('Smarts')
plt.ylabel(u'概率', fontproperties='SimHei')
plt.title(u'IQ直方圖', fontproperties='SimHei')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
結果例如以下所看到的:

All of the text() commands return an matplotlib.text.Text instance. Just as with with lines above, you can customize the properties by passing keyword arguments into the text functions or using setp():

t = plt.xlabel('my data', fontsize=14, color='red')

These properties are covered in more detail in Text properties and layout.

Using mathematical expressions in text

在文本中使用的數學表達式。matplotlib accepts TeX equation expressions in any text expression. For example to write the expression  in the title, you can write a TeX expression surrounded by dollar signs:

plt.title(r'$\sigma_i=15$')

The r preceding the title string is important – it signifies that the string is a raw string and not to treat backslashes and python escapes. matplotlib has a built-in TeX expression parser and layout engine, and ships its own math fonts – for details see Writing mathematical expressions. Thus you can use mathematical text across platforms without requiring a TeX installation. For those who have LaTeX and dvipng installed, you can also use LaTeX to format your text and incorporate the output directly into your display figures or saved postscript – see Text rendering With LaTeX.

Annotating text

The uses of the basic text() command above place text at an arbitrary position on the Axes. A common use case of text is to annotate some feature of the plot, and the annotate()method provides helper functionality to make annotations easy. In an annotation, there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext. Both of these arguments are (x,y) tuples.

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

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )

plt.ylim(-2,2)
plt.show()
結果為:


In this basic example, both the xy (arrow tip) and xytext locations (text location) are in data coordinates. There are a variety of other coordinate systems one can choose – seeAnnotating text and Annotating Axes for details. More examples can be found in pylab_examples example code: annotation_demo.py.

其它

這部分內容詳細請看:點擊打開鏈接

橫向圖形:

from matplotlib import pyplot as plt
from numpy import sin, exp,  absolute, pi, arange
from numpy.random import normal


def f(t):
    s1 = sin(2 * pi * t)
    e1 = exp(-t)
    return absolute((s1 * e1)) + .05


t = arange(0.0, 5.0, 0.1)
s = f(t)
nse = normal(0.0, 0.3, t.shape) * s

fig = plt.figure(figsize=(12, 6))
vax = fig.add_subplot(121)
hax = fig.add_subplot(122)

vax.plot(t, s + nse, 'b^')
vax.vlines(t, [0], s)
vax.set_xlabel('time (s)')
vax.set_title('Vertical lines demo')

hax.plot(s + nse, t, 'b^')
hax.hlines(t, [0], s, lw=2)
hax.set_xlabel('time (s)')
hax.set_title('Horizontal lines demo')

plt.show()
結果為:

點狀分布圖:

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

plt.scatter(x, y, s=area, alpha=0.5)
plt.show()
結果為:


總結

1、顏色控制:

b:blue ,ccyan,ggreen,kblack,mmagenta。rred ,wwhite, yyellow。


控制顏色方法:
簡稱或者全稱:如上所列。
16進制:FF00FF;
RGB或RGBA元組:(1,0,1,1);
灰度強度如:0.7;(大量顏色處理適用。不反復的隨機數就可以)

2、線型控制:

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

3、點的標記

hatch [‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’]
.  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
以上部分內容來源於:點擊打開鏈接

未完待續。

。隨時更新。

歡迎提問。共同學習,一起進步。

本文由@The_Third_Wave(Blog地址:http://blog.csdn.net/zhanh1218)原創。不定期更新,有錯誤請指正。

Sina微博關注:@The_Third_Wave 

假設這篇博文對您有幫助。為了好的網絡環境,不建議轉載,建議收藏!假設您一定要轉載。請帶上后綴和本文地址。


免責聲明!

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



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