栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Matplotlib 画分段函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Matplotlib 画分段函数

from matplotlib import pyplot as plt
import numpy as np # 导入matplotlib库的子库pyplot和numpy库

def matplotlibshow(a, b, c, d, e):  # 定义新的函数
    x = np.linspace(-25, 0, 1000)  # 确定图像中定义域的取值范围

    interval0 = [1 if (i <= a) else 0 for i in x]
    interval1 = [1 if (i <= b and i > a) else 0 for i in x]
    interval2 = [1 if (i <= c and i > b) else 0 for i in x]
    interval3 = [1 if (i <= d and i > c) else 0 for i in x]
    interval4 = [1 if (i <= e and i > d) else 0 for i in x]
    interval5 = [1 if (i > e) else 0 for i in x]  # 确定各取值区间

    y = 1 * interval0 + (0.8 + 0.2*(x - a) / (b - a)) * interval1 + (0.6 + 0.3*(x - b) / (c - b)) * interval2 + (
                0.3 + 0.2*(x - c) / (d - c)) * interval3 + (0.3*(x - d) / (e - d)) * interval4  # 写入需要画图的函数
    
    plt.plot(x, y, 'o--k', ms=1)  # 使用plot函数传入x,y,设置线条格式,粗细
    plt.xticks([a, b, c, d, e], ["a", "b", "c", "d", "e"])  # 修改横坐标内容
    plt.yticks([])  # 取消纵坐标的值
    plt.xlabel('x')  # 横轴命名
    plt.ylabel('y')  # 纵轴命名
    plt.title('Piecewise')  # 函数标题
    plt.show()

def main():
    matplotlibshow(-21, -17, -13, -9, -4)
main()

 代码运行结果如下:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/915767.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号