zoukankan      html  css  js  c++  java
  • Matplotlib基本使用

    Matplotlib是一个强大的Python绘图和数据可视化的工具包。

    安装方法pip install matplotlib

    引用方法import matplotlib.pyplot as plt

    绘图函数plt.plot()

    显示图像plt.show()

    Matplotlib-plot函数

    plot函数:绘制折线图

    • 线型linestyle -, -. ,-- , ...
    • 点型marker v, ^, S, *, H, +, x, D, o, ...
    • 颜色color b, g, r, y, k, w, ...

    plot函数绘制多条曲线

    # 线的表示
    plt.plot([1,2,5,8], [3,4,5,9], "r", label='line a')# 折线图(X, Y)
    plt.plot([1,2,4,8], [1,3,7,10], color="y", label='line b')# 折线图(X, Y)
    
    plt.legend()
    plt.show()
    

    pandas包对plot的支持

    df = pd.read_csv('zn2006SHFE2020.csv', index_col='datetime', parse_dates=['datetime'])[['open','high','low','close']]
    
    df.plot()
    plt.show()
    

    Matplotlib 图像标注

    • 设置图像标题 :plt.title()
    • 设置X轴名称:plt.xlabel()
    • 设置Y轴名称:plt.ylabel()
    • 设置X轴范围:plt.xlim()
    • 设置Y轴范围:plt.ylim()
    • 设置X轴刻度:plt.xticks()
    • 设置Y轴刻度:plt.yticks()
    • 设置曲线图例:plt.legend()

    数学函数 示例

    # 使用Matplotlib模块在一个窗口中绘制数学函数 y=x, y=x2, y=3x**3+5x**2+2x+1的图像,使用不同颜色的线加以区别,并使用图例说明各个线代表说明函数
    x = np.linspace(-1000, 1000, 10000)
    y1 = x.copy()
    y2 = x**2
    y3 = 3*x**3+5*x**2+2*x+1
    plt.plot(x, y1,'y', label='y=x')
    plt.plot(x, y2,'r', label='y2')
    plt.plot(x, y3,'b', label='y3')
    
    plt.xlim(-1000, 1000)
    plt.ylim(-1000, 1000)
    
    
    plt.legend()
    plt.show
    

    matplotlib 画布与子图

    在一个画布里画很多图

    • 画布 figure

      fig = plt.figure()

    • subplot

      ax1=fig.add_subplot(2,2,1)

    • 调解子图间距

      subplots_adjust(left, bottom, right, top, wspace, hspace)

    # 画图与子图
    fig = plt.figure() # 添加一个画布
    ax1 = fig.add_subplot(2,1,1) # 添加一个子图  2行1列  第1个位置
    ax2 = fig.add_subplot(2,1,2) # 添加一个子图  2行1列  第2个位置
    
    ax1.plot([1,2,4], [3,5,7])
    ax2.plot([1,4,7], [3,2,7])
    
    plt.show()
    

    折线图

    # 线的表示
    plt.plot([1,2,5,8], [3,4,5,9], "r", label='line a')# 折线图(X, Y)
    plt.plot([1,2,4,8], [1,3,7,10], color="y", label='line b')# 折线图(X, Y)
    
    plt.legend()
    plt.show()
    

    条形图

    # 条形图
    plt.bar([1,2,3,5],[5,6,7,8])
    
    plt.show()
    
    # 条形图2
    data= [56, 34, 22, 38]
    labels = ['Jan','Feb','Mar','Apr']
    
    plt.bar(labels, data, color='y')
    
    plt.show()
    

    饼图

    # 饼图
    plt.pie([10,20,54,99],labels=['a','b','c','d'], autopct='%.2f%%',explode=[0.2,0,0.1,0])
    
    plt.show()
    

    matplotlib 绘制K线图

    mplfinance中有许多绘制金融相关图的函数接口

    绘制K线图:mplfinance.candlestick_ochl函数

  • 相关阅读:
    .Net Core实现下载多个文件并压缩打包
    VS上使用Docker调试编译net core项目时卡在 vsdbgvs2017u5 exits,deleting.
    spring boot actuator监控详细介绍
    数仓知识
    layui使用 弹窗 layer
    Spring配置数据源(连接池)
    Spring配置文件-引入其他配置文件(分模块开发import)&Spring相关API
    Spring配置文件-Bean标签配置
    事务的四大特征&事务隔离级别
    事务
  • 原文地址:https://www.cnblogs.com/sunch/p/13221204.html
Copyright © 2011-2022 走看看