使用Python matplotlib作圖時,設置橫縱坐標軸數(shù)值以百分比(%)顯示
一、當我們用Python matplot時作圖時,一些數(shù)據(jù)需要以百分比顯示,以更方便地對比模型的性能提升百分比。
二、借助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()
圖形顯示如下:

現(xiàn)在我們將橫縱坐標變成百分比形式即,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的代碼,執(zhí)行結果如下:

可見已經(jīng)實現(xiàn)我們的需求。
重要代碼
return '%1.0f'%(10*temp) + '%' #這句話指定了顯示的格式。
更多格式化顯示,可以查看matplotlib.ticker。
補充知識:matplotlib畫圖系列之設置坐標軸(精度、范圍,標簽,中文字符顯示)
在使用matplotlib模塊時畫坐標圖時,往往需要對坐標軸設置很多參數(shù),這些參數(shù)包括橫縱坐標軸范圍、坐標軸刻度大小、坐標軸名稱等
在matplotlib中包含了很多函數(shù),用來對這些參數(shù)進行設置。
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']
#創(chuàng)建數(shù)據(jù)
x = np.linspace(-5, 5, 100)
y1 = np.sin(x)
y2 = np.cos(x)
#創(chuàng)建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 matplotlib作圖時,設置橫縱坐標軸數(shù)值以百分比(%)顯示就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Django實現(xiàn)WebSSH操作物理機或虛擬機的方法
這篇文章主要介紹了Django實現(xiàn)WebSSH操作物理機或虛擬機的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11
SVM算法的理解及其Python實現(xiàn)多分類和二分類問題
這篇文章主要介紹了SVM算法的理解及其Python實現(xiàn)多分類和二分類問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
一文了解python 3 字符串格式化 F-string 用法
本文介紹在python 3 編程中,如何進行字符串格式化。介紹了F-string的用法,通過實例代碼給大家介紹的非常詳細,對大家的工作或?qū)W習具有一定的參考借鑒價值,需要的朋友參考下吧2020-03-03

