python中画图-matplotlib

通常我们得到数据之后,很想以图的直观形式展现给老板或者其他同事同学,那MATLAB的画图工具很强大,各种图形都能话,那python其实也带的有类似的画图库-matplotlib,用pip安装一下就可以用啦。

我们看看几个例子怎么用吧。Reference:https://www.cnblogs.com/zhizhan/p/5615947.html

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

# 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

# ticks is using map to change 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$'])

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
# ticks is using map to change 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$'])

# 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()

效果如下:

嗨哟其他的一些函数的使用,大家可以参考官方文档:https://matplotlib.org/api/pyplot_api.html#matplotlib

猜你喜欢

转载自blog.csdn.net/lwc5411117/article/details/83549187