首页 > 其他 > 详细

pyplot 作图总结

时间:2020-02-06 21:49:03      阅读:84      评论:0      收藏:0      [点我收藏+]

折线图

下面是绘制折线图,设置图片的横轴纵轴标签,图片标题的API的用法。

import matplotlib.pyplot as pyplot


# init
pyplot.figure()

# arguments
x_label = 'X-label'
y_label = 'Y-label'
title = 'Demo-title'

# points data
x = [1, 2, 3, 4]
y = [45, 32, 46, 89]

# set arguments
pyplot.xlabel(x_label)
pyplot.ylabel(y_label)
pyplot.title(title)

# set data
pyplot.plot(x, y)

pyplot.show()

多个函数图像

import matplotlib.pyplot as pyplot
import numpy

# init
pyplot.figure()

# arguments
x_label = 'x'
y_label = 'sin(x)'
title = 'Figure-sin(x)'

# points data
# [0, 10] 区间内的 1000 个均匀分布的 x
x = numpy.linspace(0, 10, 1000)
sin_y = numpy.sin(x)
cos_y = numpy.cos(x)

# set arguments
pyplot.xlabel(x_label)
pyplot.ylabel(y_label)
pyplot.title(title)


# 设置 y 轴范围
pyplot.ylim(-1.5, 1.5)


# set data
# label, color, linewidth 是 图示 参数,用于区分多个曲线的情况
pyplot.plot(x, sin_y, label='$ sin(x) $', color='red', linewidth=1)
pyplot.plot(x, cos_y, label='$ cos(x) $', color='blue', linewidth=1)
pyplot.legend()

pyplot.show()

多个函数图像 2.0

在上述基础上进一步封装, 对 draw_arguments 进行实例化, 然后调用 draw_figure 即可.

import matplotlib.pyplot as pyplot
import numpy
import math


class draw_arguments:

    def __init__(self, func, func_name, x_domain: tuple, points_num=1000):
        super().__init__()
        self.draw_func = func
        self.func_name = func_name
        self.x_data = numpy.linspace(x_domain[0], x_domain[1], points_num)
        self.y_data = [func(x) for x in self.x_data]


def draw_figure(dargs, title='Figure', x_label='x', y_label='y'):
    # init
    pyplot.figure()

    # set arguments
    pyplot.xlabel(x_label)
    pyplot.ylabel(y_label)
    pyplot.title(title)

    # set data
    # label, color, linewidth 是 图示 参数,用于区分多个曲线的情况
    for draw in dargs:
        pyplot.plot(draw.x_data, draw.y_data, label='$' +
                    draw.func_name + '$', linewidth=1)
    pyplot.legend()

    pyplot.show()


d1 = draw_arguments(func=lambda x: 2**x,
                    func_name='2^x',
                    x_domain=(0, 5))

d2 = draw_arguments(func=lambda x: x*x,
                    func_name='x^2',
                    x_domain=(0, 5))

draw_figure([d1, d2])

pyplot 作图总结

原文:https://www.cnblogs.com/sinkinben/p/12269988.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!