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

    Matplotlib是一款专门用于开发2D图表(包括3D图表)、以渐进、交互方式实现数据可视化的工具。

    Matplotlib的基本使用:

    1. 安装Matplotlib

    最好准备一个虚拟环境来用。

    workon ai_study
    
    pip install matplotlib

     2. 使用Matplotlib绘制图形

    # 0. 导入模块
    import matploatlib.pyplot as plt
    
    # 1. 创建画布
    plt.figure(figsize=(), dpi=)
        # figsize:指定图的长宽
        # dpi:图像的清晰度
        # 返回fig对象
    
    # 2. 绘制折线图
    plt.plot(x,y)
    
    # 3. 显示图像
    plt.show()

    3. 自定义x,y刻度

    • plt.xticks(x, **kwargs)

      x:要显示的刻度值

    • plt.yticks(y, **kwargs)

      y:要显示的刻度值

    # 增加以下两行代码
    
    # 构造x轴刻度标签
    x_ticks_label = ["11点{}分".format(i) for i in x]
    # 构造y轴刻度
    y_ticks = range(40)
    
    # 修改x,y轴坐标的刻度显示
    plt.xticks(x[::5], x_ticks_label[::5])
    plt.yticks(y_ticks[::5])

    4. 解决中文显示不出来的问题

    解决方案一:

    下载中文字体(黑体,看准系统版本)

    • 步骤一:下载 SimHei 字体(或者其他的支持中文显示的字体也行)

    • 步骤二:安装字体

      • linux下:拷贝字体到 usr/share/fonts 下:

        sudo cp ~/SimHei.ttf /usr/share/fonts/SimHei.ttf
      • windows和mac下:双击安装

    • 步骤三:删除~/.matplotlib中的缓存文件

      cd ~/.matplotlib
      rm -r *
    • 步骤四:修改配置文件matplotlibrc

      vi ~/.matplotlib/matplotlibrc

      将文件内容修改为:

      font.family         : sans-serif
      font.sans-serif         : SimHei
      axes.unicode_minus  : False

    解决方案二:

    在Python脚本中动态设置matplotlibrc,这样也可以避免由于更改配置文件而造成的麻烦,具体代码如下:

    from pylab import mpl
    # 设置显示中文字体
    mpl.rcParams["font.sans-serif"] = ["SimHei"]

    有时候,字体更改后,会导致坐标轴中的部分字符无法正常显示,此时需要更改axes.unicode_minus参数:

    # 设置正常显示符号
    mpl.rcParams["axes.unicode_minus"] = False

    5. 添加网格显示

    plt.grid(True, linestyle='--', alpha=0.5)

     6. 添加描述信息

    plt.xlabel("时间")
    plt.ylabel("温度")
    plt.title("中午11点--12点某城市温度变化图", fontsize=20)

      7. 添加图例

    plt.legend(loc=0,fontsize=18)

      图例位置表

    Location StringLocation Code
    'best' 0
    'upper right' 1
    'upper left' 2
    'lower left' 3
    'lower right' 4
    'right' 5
    'center left' 6
    'center right' 7
    'lower center' 8
    'upper center' 9
    'center' 10
     
  • 相关阅读:
    解决 Mac launchpad 启动台 Gitter 图标无法删除的问题
    React 与 React-Native 使用同一个 meteor 后台
    解决 React-Native mac 运行报错 error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by ope
    一行命令更新所有 npm 依赖包
    swift学习笔记
    IOS语言总结
    focusSNS学习笔记
    别小看锤子,老罗真的很认真
    windowsphone开发页面跳转到另一个dll中的页面
    【令人振奋】【转】微软潘正磊谈DevOps、Visual Studio 2013新功能、.NET未来
  • 原文地址:https://www.cnblogs.com/chao666/p/12588183.html
Copyright © 2011-2022 走看看