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

本文介绍了如何在matplotlib中设置y轴显示为百分比格式。通过`plt.gca().yaxis.set_major_formatter()`或`ax.yaxis.set_major_formatter()`方法,结合`ticker.PercentFormatter`,可以将数据图的y轴转换为百分比展示。示例代码分别展示了使用plt和ax两种方式实现,最终结果显示两种方法的效果相同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、思路

        在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轴显示百分比

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞机火车巴雷特

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值