欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

使用Python matplotlib作图时,设置横纵坐标轴数值以百分比(%)显示

时间:2021-05-05 15:34:43|栏目:Python代码|点击:

一、当我们用Python matplot时作图时,一些数据需要以百分比显示,以更方便地对比模型的性能提升百分比。

二、借助matplotlib.ticker.FuncFormatter(),将坐标轴格式化。

例子:

# encoding=utf-8
import matplotlib.pyplot as plt 
from matplotlib.ticker import FuncFormatter
plt.rcParams['font.family'] = ['Times New Roman']
plt.rcParams.update({'font.size': 8}) 
x = range(11)
y = range(11)
plt.plot(x, y)
plt.show()

图形显示如下:

现在我们将横纵坐标变成百分比形式即,0%,20%,40%....代码如下:

# encoding=utf-8
import matplotlib.pyplot as plt 
from matplotlib.ticker import FuncFormatter
plt.rcParams['font.family'] = ['Times New Roman']
plt.rcParams.update({'font.size': 8}) 
x = range(11)
y = range(11)
plt.plot(x, y)
 
def to_percent(temp, position):
  return '%1.0f'%(10*temp) + '%'
plt.gca().yaxis.set_major_formatter(FuncFormatter(to_percent))
plt.gca().xaxis.set_major_formatter(FuncFormatter(to_percent))
 
plt.show()

即增加了10~13的代码,执行结果如下:

可见已经实现我们的需求。

重要代码

return '%1.0f'%(10*temp) + '%' #这句话指定了显示的格式。

更多格式化显示,可以查看matplotlib.ticker

补充知识:matplotlib画图系列之设置坐标轴(精度、范围,标签,中文字符显示)

在使用matplotlib模块时画坐标图时,往往需要对坐标轴设置很多参数,这些参数包括横纵坐标轴范围、坐标轴刻度大小、坐标轴名称等

在matplotlib中包含了很多函数,用来对这些参数进行设置。

plt.xlim、plt.ylim 设置横纵坐标轴范围
plt.xlabel、plt.ylabel 设置坐标轴名称
plt.xticks、plt.yticks设置坐标轴刻度

以上plt表示matplotlib.pyplot

例子

#导入包
import matplotlib.pyplot as plt
import numpy as np
#支持中文显示
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
 
#创建数据
x = np.linspace(-5, 5, 100)
y1 = np.sin(x)
y2 = np.cos(x)
 
#创建figure窗口
plt.figure(num=3, figsize=(8, 5))
#画曲线1
plt.plot(x, y1)
#画曲线2
plt.plot(x, y2, color='blue', linewidth=5.0, linestyle='--')
#设置坐标轴范围
plt.xlim((-5, 5))
plt.ylim((-2, 2))
#设置坐标轴名称
plt.xlabel('xxxxxxxxxxx')
plt.ylabel('yyyyyyyyyyy')
#设置坐标轴刻度
my_x_ticks = np.arange(-5, 5, 0.5)
my_y_ticks = np.arange(-2, 2, 0.3)
plt.xticks(my_x_ticks)
plt.yticks(my_y_ticks)
 
#显示出所有设置
plt.show()

结果

上一篇:Python实现自定义读写分离代码实例

栏    目:Python代码

下一篇:详解python3类型注释annotations实用案例

本文标题:使用Python matplotlib作图时,设置横纵坐标轴数值以百分比(%)显示

本文地址:http://www.codeinn.net/misctech/114842.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有