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

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

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

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

一、思路

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

import matplotlib.pyplot as plt
from matplotlib import ticker

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

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

        对于ax,需要这样设置

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

二、plt

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

import matplotlib.pyplot as plt
from matplotlib import ticker

# data
a_list = [0, 10, 20, 30, 40, 50, 60, 70, 80]
b_list = [0.25, 0.50, 0.90, 0.90, 1.00, 0.90, 1.00, 0.95, 0.95]

# figure configurations
plt.rcParams.update({"font.size": 16})
plt.figure(figsize=(8, 8))
plt.ylim(0.0, 1.1)

# set y axis a format of percentage
plt.gca().yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1, decimals=1))

# plot a figure
plt.plot(a_list, b_list, linewidth=3.0, marker='^', ms=10)

# show the figure
plt.legend()
plt.show()

        效果是这样的

三、ax

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

import matplotlib.pyplot as plt
from matplotlib import ticker

# data
a_list = [0, 10, 20, 30, 40, 50, 60, 70, 80]
b_list = [0.25, 0.50, 0.90, 0.90, 1.00, 0.90, 1.00, 0.95, 0.95]

# figure configurations
fig, ax = plt.subplots(figsize=(8, 8))
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
ax.set_ylim(0.0, 1.1)

# set y axis a format of percentage
ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1, decimals=1))

# plot a figure
ax.plot(a_list, b_list, linewidth=3.0, marker='^', ms=10)

# show the figure
ax.legend(fontsize=16)
plt.show()

        效果是这样的

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

四、参考

        1、Matplotliby轴显示百分比形式

        2、python matplotlib y轴显示百分比

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

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

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