Matplotlib绘图可视化——Python

今天在绘制曲线时遇到了一个问题,绘图完成后,图像保存后,发现调用show()方法无法显示绘图窗口,后来调试很多次,发现必须在保存图像之前调用show()方法才能调出绘图窗口。

  • 以下为在同一个绘图对象中绘图
import matplotlib
import math
x = list()
y1 = list()
y2 = list()
#收集x和y的数据
num = 0
while num < math.pi * 4:
  x.append(num)
  y1.append(math.sin(num))
  y2.append(math.cos(num))
  num += 0.1
#将曲线画在同一幅图中
matplotlib.pyplot.figure(0, figsize = (8, 6), dpi = 100) #建立绘图对象,当前绘图对象为figure0,图像大小800*600
matplotlib.pyplot.plot(x, y1, 'b-', linewidth = 1.0, label = 'y = sin(x)') #在当前绘图对象中绘图
matplotlib.pyplot.plot(x, y2, 'r--', linewidth = 1.0, label = 'y = cos(x)') #在当前绘图对象中绘图
matplotlib.pyplot.xlabel('x') #设置x轴标签
matplotlib.pyplot.ylabel('y') #设置y轴标签
matplotlib.pyplot.legend() #显示图例
matplotlib.pyplot.title('example') #设置标题
matplotlib.pyplot.grid(True) #显示网格
#注意在保存图像之前调用show()方法,否则无法显示绘图窗口
matplotlib.pyplot.show() #调出绘图窗口,显示图像
matplotlib.pyplot.savefig('sin.jpg') #保存图片

若不使用figure()方法建立绘图对象,则用plot()绘图时会自动建立,此时所有的图形都默认绘制在一个绘图对象中。

  • 绘图窗口显示如下:
    Matplotlib绘图可视化——Python
  • 注意,保存图像之后是无法显示绘图窗口的,应该在保存图像之前电泳show()方法,才能调出绘图窗口。
  • 也可以在不同的图形中绘制曲线,这时就需要建立两个绘图对象。将程序改为:
import matplotlib
import math
x = list()
y1 = list()
y2 = list()
#收集x和y的数据
num = 0
while num < math.pi * 4:
  x.append(num)
  y1.append(math.sin(num))
  y2.append(math.cos(num))
  num += 0.1
#将曲线分别画在两幅图中
#sin(x)
matplotlib.pyplot.figure(0, figsize = (8, 6), dpi = 100) #当前绘图对象为figure0
matplotlib.pyplot.plot(x, y1, 'b-', linewidth = 1.0, label = 'y = sin(x)')
matplotlib.pyplot.xlabel('x') #设置x轴标签
matplotlib.pyplot.ylabel('y') #设置y轴标签
matplotlib.pyplot.legend() #显示图例
matplotlib.pyplot.title('example0') #设置标题
matplotlib.pyplot.grid(True) #显示网格 #在当前绘图对象中绘图
#cos(x)
matplotlib.pyplot.figure(1, figsize = (8, 6), dpi = 100) #当前绘图对象为figure1
matplotlib.pyplot.plot(x, y2, 'r--', linewidth = 1.0, label = 'y = cos(x)') #在当前绘图对象中绘图
matplotlib.pyplot.xlabel('x') #设置x轴标签
matplotlib.pyplot.ylabel('y') #设置y轴标签
matplotlib.pyplot.legend() #显示图例
matplotlib.pyplot.title('example1') #设置标题
matplotlib.pyplot.grid(True) #显示网格
#注意在保存图像之前调用show()方法,否则无法显示绘图窗口
matplotlib.pyplot.show() #调出绘图窗口,显示图像
matplotlib.pyplot.savefig('sin.jpg') #保存图片
  • 绘图窗口显示如下
    Matplotlib绘图可视化——Python
    Matplotlib绘图可视化——Python