python中畫圖-matplotlib
阿新 • • 發佈:2018-12-18
通常我們得到資料之後,很想以圖的直觀形式展現給老闆或者其他同事同學,那MATLAB的畫圖工具很強大,各種圖形都能話,那python其實也帶的有類似的畫相簿-matplotlib,用pip安裝一下就可以用啦。
1. 餅圖
#!/usr/bin/python import matplotlib.pyplot as plt labels='Tanh','ReLu','Sigmoid' # define label of each part to show on pie sizes=25,30,45 # define size of each part colors='yellowgreen','lightskyblue','lightcoral' # define color of each part on pie explode=0,0,0.1 # define which one will be exploded plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50) # plot pie plt.axis('equal') # axis type plt.show() # draw and show
效果如下:
2. 畫函式曲線
#!/usr/bin/python import matplotlib.pyplot as plt import numpy as np from pylab import * x = np.arange(-10.0, 10.0, 0.1) y1 = np.sin(x) # define sin function # plot first sin function plt.subplot(211) # draw on which window plt.plot(x, y1) # draw line # plot second function with smaller axis than first plt.subplot(212) # draw on which window plt.plot(x, y1) # draw line # set under the plot function to affect window axis xlim(-5.0, 5.0) # set x axis range ylim(-1, 1) # set y axis range # show window plt.show()
結果如下:
3. 線型
#!/usr/bin/python import matplotlib.pyplot as plt import numpy as np from pylab import * x = np.arange(-100.0, 100.0, 0.2) # draw 3 line on same graph with different color # color: b->blue, g->green, r-red, y->yellow, c->cyan, k->black, m->magenta, w->white # line style: '-'->solid line, ':'->dotted line, '–'->dash line, '-.'->dotted dash line, 'None' or ','-> empty # marker: 'o'->circle, '.'->dot, 'd'-> little diamond, 'D'->diamond, 's'->square, 'h'->hexagon 1, 'H'->hexagon 2, # : '*'->star, '_'->horizontal line, 'v'->downard triangle, 'v'->upward triangle, '<'->left triangle, '>'->right triangle # : '8'->octagon, 'p'->pentagon, ','->pixel, '+'->plus sign, '\'->', 'None' or ','-> empty, 'x'->X plt.plot(x, x, 'r--', x, x**2, 'g*', x, x**3, 'bv') plt.axis([-100, 100, -100, 100]) # draw a title plt.title('Draw 3 line on same graph', color='#123456') # show window plt.show()
結果如下:
4. 使用figure開啟新的視窗
#!/usr/bin/python
import matplotlib.pyplot as plt
# we can use "figure" function to open new window and switch between windows
plt.figure(1) # open first window
plt.subplot(211) # select first canvas in first window
plt.plot([1,2,3]) # draw on first canvas in first window
plt.subplot(212) # select second canvas in first window
plt.plot([4,5,6]) # draw on second canvas in first window
plt.figure(2) # open second window
plt.plot([4,5,6]) # draw on canvas, default is subplot(111)
plt.figure(1) # switch to first window, but current canvas id is still 212
plt.title('second canvas') # draw on second canvas
plt.subplot(211) # switch to first canvas
plt.title('first canvas') # draw title for first canvas
plt.show() # show window
結果如下:
5. 畫文字
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 50, 20 # define Gaussian distribution parameter
x = mu + sigma * np.random.randn(10000) # generate Gaussian distribution
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75) # plot histogram
plt.xlabel('Score') # plot x label
plt.ylabel('Probability') # plot y label
plt.title('Histogram of Score') # plot title
plt.text(20, .025, '$\mu=100, \ \sigma=15$') # add text
plt.axis([0, 100, 0, 0.03]) # set x and y axis
plt.grid(True) # draw grid
plt.show() # show window
結果如下:
6. 畫annotation
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
ax = plt.subplot(111)
x = np.arange(-5.0, 5.0, 0.01) # generate x vector
y = np.cos(2*np.pi*x) # generate y vector with x vector
line, = plt.plot(x, y, lw=1) # draw line with line weight 1
# add annotation:
# first parameteris test to show
# second xy is the position of arraw pointer
# third xytest is the position of annotation to show
# fourth arrowprops is properties of arrow
plt.annotate('local max on cos function', xy=(0, 1), xytext=(1, 1.5), arrowprops=dict(facecolor='green', shrink=0.01),)
plt.xlim(-5, 5) # limit x axis
plt.ylim(-2, 2) # limit y axis
plt.show() # show window
結果如下:
7. 用ticks改變座標標籤
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
plt.subplot(111) # select first canvas
x = np.arange(-5.0, 5.0, 0.01) # generate x vector
ycos = np.cos(2*np.pi*x) # generate y vector with x vector
ysin = np.sin(2*np.pi*x) # generate y vector with x vector
plt.plot(x, ycos, lw=1, color='blue') # draw line with line weight 1
plt.plot(x, ysin, lw=1, color='red') # draw line with line weight 1
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) # ticks is using map to change label
plt.yticks([-1, 0, 1],
[r'$-1$', r'$0$', r'$1$']) # ticks is using map to change label
plt.xlim(-5, 5) # limit x axis
plt.ylim(-2, 2) # limit y axis
plt.show() # show window
結果如下:
8. 平移座標系
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
plt.subplot(111) # select first canvas
x = np.arange(-5.0, 5.0, 0.01) # generate x vector
ycos = np.cos(2*np.pi*x) # generate y vector with x vector
ysin = np.sin(2*np.pi*x) # generate y vector with x vector
plt.plot(x, ycos, lw=1, color='blue') # draw line with line weight 1
plt.plot(x, ysin, lw=1, color='red') # draw line with line weight 1
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) # ticks is using map to change label
plt.yticks([-1, 0, 1],
[r'$-1$', r'$0$', r'$1$']) # ticks is using map to change label
plt.xlim(-5, 5) # limit x axis
plt.ylim(-2, 2) # limit y axis
ax = plt.gca() # get axis
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
plt.show() # show window
結果如下
9. 增加圖例
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
# 1. draw lines
plt.subplot(111) # select first canvas
x = np.arange(-5.0, 5.0, 0.01) # generate x vector
ycos = np.cos(2*np.pi*x) # generate y vector with x vector
ysin = np.sin(2*np.pi*x) # generate y vector with x vector
plt.plot(x, ycos, color='blue', linewidth=1, linestyle='-', label='cosine') # draw line with line weight 1
plt.plot(x, ysin, color='red', linewidth=1, linestyle='-', label='sine') # draw line with line weight 1
plt.legend(loc='upper left') # draw legend
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) # ticks is using map to change label
plt.yticks([-1, 0, 1],
[r'$-1$', r'$0$', r'$1$']) # ticks is using map to change label
plt.xlim(-5, 5) # limit x axis
plt.ylim(-2, 2) # limit y axis
plt.show() # show window
結果如下:
10. 散點圖
#!/usr/bin/python
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import datasets
from sklearn import linear_model
import numpy as np
# load data
boston = datasets.load_boston()
Xb = boston['data'][:, 5].reshape(-1, 1)
yb = boston.target.reshape(-1, 1)
# plot data
plt.style.use('ggplot') # using ggplot style
plt.scatter(Xb, yb)
plt.xlabel('number of rooms')
plt.ylabel('value of house / 1000 ($)')
#create line regression object
regr = linear_model.LinearRegression()
# train the model using the training sets
regr.fit(Xb, yb)
# plot output
plt.scatter(Xb, yb, color='blue') # plot scatter diagram
plt.plot(Xb, regr.predict(Xb), color='green', linewidth=2)
plt.show() # show window
結果如下:
11. 標註
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
# 1. draw line
plt.subplot(111) # select first canvas
x = np.arange(-4.0, 4.0, 0.01) # generate x vector
ycos = np.cos(x) # generate y vector with x vector
ysin = np.sin(x) # generate y vector with x vector
plt.plot(x, ycos, color='blue', linewidth=1, linestyle='-', label='cosine') # draw line with line weight 1
plt.plot(x, ysin, color='red', linewidth=1, linestyle='-', label='sine') # draw line with line weight 1
# 2. draw legend
plt.legend(loc='upper left') # draw legend
# 3. draw axis label
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) # ticks is using map to change label
plt.yticks([-1, 0, 1],
[r'$-1$', r'$0$', r'$1$']) # ticks is using map to change label
# 4. reset axis
ax = plt.gca() # get axis
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
# 5. draw annotation
px = 2 * np.pi / 3
plt.plot([px, px], [0, np.cos(px)], color='blue', linewidth=1, linestyle='--')
plt.scatter([px,], [np.cos(px),], 50, color='blue')
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(px, np.sin(px)), xycoords='data',
xytext=(+10, +30), textcoords='offset points',
fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
plt.plot([px, px], [0,np.sin(px)], color='red', linewidth=1, linestyle='--')
plt.scatter([px,], [np.sin(px),], 50, color='red')
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(px, np.cos(px)), xycoords='data',
xytext=(-90, -50), textcoords='offset points',
fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
# 6. show window
plt.show()
效果如下: