• 设置matplotlib绘图的y轴为百分比格式


    一、思路

            在matplotlib中存在两种绘图方法,一种是利用“matplotlib.pyplot as plt”中的plt进行绘图,这种只能够绘制一张图片;而另外一种是利用“fig, ax = plt.subplots()”中的ax进行绘图,这种能够绘制一张或者多张图片。平时我们可能会接触到百分比数据,这时我们期望绘制一个带有百分号的数据图。主要的思路是通过set_major_formatter()这个函数对plt或ax进行设置。首先,我们需要导入以下的包

    1. import matplotlib.pyplot as plt
    2. from matplotlib import ticker

            然后,我们需要对plt或者ax进行设置。对于plt,需要这样设置

    plt.gca().yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1, decimals=1))

            对于ax,需要这样设置

    1. fig, ax = plt.subplots()
    2. ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1, decimals=1))

    二、plt

            我对上面两种方法分别进行测试,第一个是plt,对应的全部代码为

    1. import matplotlib.pyplot as plt
    2. from matplotlib import ticker
    3. # data
    4. a_list = [0, 10, 20, 30, 40, 50, 60, 70, 80]
    5. b_list = [0.25, 0.50, 0.90, 0.90, 1.00, 0.90, 1.00, 0.95, 0.95]
    6. # figure configurations
    7. plt.rcParams.update({"font.size": 16})
    8. plt.figure(figsize=(8, 8))
    9. plt.ylim(0.0, 1.1)
    10. # set y axis a format of percentage
    11. plt.gca().yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1, decimals=1))
    12. # plot a figure
    13. plt.plot(a_list, b_list, linewidth=3.0, marker='^', ms=10)
    14. # show the figure
    15. plt.legend()
    16. plt.show()

            效果是这样的

    三、ax

            第二是ax,对应的全部代码为

    1. import matplotlib.pyplot as plt
    2. from matplotlib import ticker
    3. # data
    4. a_list = [0, 10, 20, 30, 40, 50, 60, 70, 80]
    5. b_list = [0.25, 0.50, 0.90, 0.90, 1.00, 0.90, 1.00, 0.95, 0.95]
    6. # figure configurations
    7. fig, ax = plt.subplots(figsize=(8, 8))
    8. plt.xticks(fontsize=16)
    9. plt.yticks(fontsize=16)
    10. ax.set_ylim(0.0, 1.1)
    11. # set y axis a format of percentage
    12. ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1, decimals=1))
    13. # plot a figure
    14. ax.plot(a_list, b_list, linewidth=3.0, marker='^', ms=10)
    15. # show the figure
    16. ax.legend(fontsize=16)
    17. plt.show()

            效果是这样的

            可以发现,这两种的效果一样。

    四、参考

            1、Matplotliby轴显示百分比形式

            2、python matplotlib y轴显示百分比

  • 相关阅读:
    20221126给Chrome浏览器安装扩展程序——猫抓
    PDF有限制不能复制怎么办?
    数据标准详细概述-2022
    使用soapUI获取webservice接口的调用格式
    SpringCloud 下 MultipartFile 序列化(JSON)出错的解决方案
    HTML+CSS简单漫画网页设计成品--(红猪(9页)带注释)
    Java大整数乘法知识点(含面试大厂题和源码)
    应广单片机(MCU单片机科普)
    怎么把家里闲置旧苹果手机变成家用安防监控摄像头
    基于libopenh264 codec的svc分层流实现方案
  • 原文地址:https://blog.csdn.net/qq_36158230/article/details/125414030