使用Python matplotlib作圖時,設(shè)置橫縱坐標軸數(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í)行結(jié)果如下:
可見已經(jīng)實現(xiàn)我們的需求。
重要代碼
return '%1.0f'%(10*temp) + '%' #這句話指定了顯示的格式。
更多格式化顯示,可以查看matplotlib.ticker。
補充知識:matplotlib畫圖系列之設(shè)置坐標軸(精度、范圍,標簽,中文字符顯示)
在使用matplotlib模塊時畫坐標圖時,往往需要對坐標軸設(shè)置很多參數(shù),這些參數(shù)包括橫縱坐標軸范圍、坐標軸刻度大小、坐標軸名稱等
在matplotlib中包含了很多函數(shù),用來對這些參數(shù)進行設(shè)置。
plt.xlim、plt.ylim 設(shè)置橫縱坐標軸范圍
plt.xlabel、plt.ylabel 設(shè)置坐標軸名稱
plt.xticks、plt.yticks設(shè)置坐標軸刻度
以上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='--') #設(shè)置坐標軸范圍 plt.xlim((-5, 5)) plt.ylim((-2, 2)) #設(shè)置坐標軸名稱 plt.xlabel('xxxxxxxxxxx') plt.ylabel('yyyyyyyyyyy') #設(shè)置坐標軸刻度 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) #顯示出所有設(shè)置 plt.show()
結(jié)果
以上這篇使用Python matplotlib作圖時,設(shè)置橫縱坐標軸數(shù)值以百分比(%)顯示就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
10分鐘用python搭建一個超好用的CMDB系統(tǒng)
這篇文章主要介紹了10分鐘用python搭建一個超好用的CMDB系統(tǒng),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07基于python+pandoc實現(xiàn)html批量轉(zhuǎn)word
pandoc是一個強大的文檔格式轉(zhuǎn)換工具,支持豐富的格式轉(zhuǎn)換,并盡可能的保留原來的排版,號稱文檔格式轉(zhuǎn)換的瑞士軍刀,本文將給大家介紹一下使用python搭配pandoc實現(xiàn)html批量轉(zhuǎn)word,感興趣的朋友可以參考閱讀下2023-09-09