使用使用Python matplotlib作图时作图时,设置横纵坐标轴数值以百分比设置横纵坐标轴数值以百分比
(%)显示显示
一、当我们用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']
评论0