安装

安装numpy

  1. pip3 install numpy

安装matplotlib

  1. pip3 install matplotlib

基础

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x1 = np.linspace(-3, 3)
  4. y1 = 2*x1-2
  5. y2 = -2*x1-2
  6. plt.plot(x1, y1)
  7. plt.plot(x1, y2)
  8. plt.show()

Matplotlib的使用 - 图1

设置坐标轴

plt.xlim设置x坐标轴范围
plt.ylim设置y坐标轴范围
plt.xlabel设置x坐标轴名称
plt.ylabel设置y坐标轴名称
plt.xticks设置x轴刻度
plt.yticks设置y轴刻度

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x = np.linspace(-3, 3,)
  4. y1 = 2 *x+1
  5. y2 = x**2
  6. plt.figure()
  7. plt.plot(x,y2)
  8. plt.plot(x,y1,color='red', linewidth=1.0, linestyle='--')
  9. plt.xlim(-1,2)
  10. plt.ylim(-2,3)
  11. plt.xlabel('x')
  12. plt.ylabel('y')
  13. new_ticks = np.linspace(-1,2,5)
  14. print(new_ticks)
  15. plt.xticks(new_ticks)
  16. plt.yticks([-2,-1.8,-1,1.22,3])
  17. plt.show()

Matplotlib的使用 - 图2

设置边框

plt.gca获取当前坐标轴信息. 使用.spines设置边框,使用.set_color设置边框颜色:默认白色.

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x = np.linspace(-3, 3)
  4. y1 = 2 *x+1
  5. plt.plot(x,y1)
  6. plt.xlim(-1,2)
  7. plt.ylim(-2,3)
  8. ax = plt.gca()
  9. ax.spines['top'].set_color('none')
  10. ax.spines['right'].set_color('none')
  11. plt.show()

Matplotlib的使用 - 图3

调整坐标轴位置

使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置(所有位置:top,bottom,both,default,none)。使用.set_position设置边框位置:y=0的位置;(位置所有属性:outward,axes,data)

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x = np.linspace(-3, 3)
  4. y1 = x**2
  5. plt.plot(x,y1)
  6. plt.xlim(-3,3)
  7. plt.ylim(-1,3)
  8. ax = plt.gca()
  9. ax.xaxis.set_ticks_position('bottom')
  10. ax.spines['top'].set_color('none')
  11. ax.spines['right'].set_color('none')
  12. ax.spines['left'].set_position(('data', 0))
  13. ax.spines['bottom'].set_position(('data', 0))
  14. plt.show()

Matplotlib的使用 - 图4

图例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x = np.linspace(-3, 3)
  4. y1 = x**2
  5. l1, = plt.plot(x,y1,label='square line')
  6. y2 = 2*x + 1
  7. l2, = plt.plot(x,y2,color='red', linewidth=1.0, linestyle='--', label='linear line')
  8. plt.xlim(-3,3)
  9. plt.ylim(-1,3)
  10. #plt.legend(loc='lower right')
  11. plt.legend(handles=[l1, l2], labels=['x^2', '2*x+1'], loc='best')
  12. ax = plt.gca()
  13. ax.xaxis.set_ticks_position('bottom')
  14. ax.spines['top'].set_color('none')
  15. ax.spines['right'].set_color('none')
  16. ax.spines['left'].set_position(('data', 0))
  17. ax.spines['bottom'].set_position(('data', 0))
  18. plt.show()

l1, l2,要以逗号结尾, 因为plt.plot() 返回的是一个列表.
位置信息

  1. =============== =============
  2. Location String Location Code
  3. =============== =============
  4. 'best' 0
  5. 'upper right' 1
  6. 'upper left' 2
  7. 'lower left' 3
  8. 'lower right' 4
  9. 'right' 5
  10. 'center left' 6
  11. 'center right' 7
  12. 'lower center' 8
  13. 'upper center' 9
  14. 'center' 10
  15. =============== =============

Matplotlib的使用 - 图5