1. 程式人生 > >matplotlib繪圖,設定座標格式,比如科學計數法、公式表示等

matplotlib繪圖,設定座標格式,比如科學計數法、公式表示等

matplotlib繪圖

前言

繪製實驗結果時,很多時候預設設定得到的圖形,並不能滿足我們的需求。如果我們希望繪製出來的圖形更加騷一點,更好看一點,我們怎麼做呢。接下來我將介紹繪圖時設定橫縱座標的表示方式,包括使用科學計數法和用公式表示方法的。

  • 科學計數表示的縱座標
    科學計數

匯入必要包

匯入必要的包,其中FuncFormatter就是設定座標格式的函式

import seaborn as sns
import matplotlib.
pyplot as plt from matplotlib.ticker import FuncFormatter ### 今天的主角 import numpy as np sns.set_style('whitegrid') ###可以設定白色網格風格使圖形更漂亮

未設定座標格式

下面為未設定座標格式的程式碼,我們可以得到相應的實驗結果。

A = np.random.randint(10000, 50000, size=(1000))
f, ax = plt.subplots(1, 1)
ax.scatter(range(len(A)), A , color='k', label='A',
marker='o', s=10) ax.set_xlim([0, 1000]) plt.show()
  • 結果
    繪圖結果

科學計數表示

下面程式碼的核心主要在FuncFormatter, 可以看出formatnum包含兩個引數,x就是我們的座標值,pos是位置。return返回的字串就是我們想要的表示形式。如果瞭解過latex,可以看出公式的部分主要和latex的表示方式相近,$$錢號裡面寫我們要表達的格式, $10^{4} $就是我們要的指數表示。 $ .1f% $是係數,其實去除錢號也行,可是會導致字型大小不一樣,所以這裡就沒有去除。

  • 這裡只寫了y座標的表示,控制x也一樣
A = np.random.randint(10000, 50000, size=(1000))
f, ax = plt.subplots(1, 1)
ax.scatter(range(len(A)), A , color='k', label='A', marker='o', s=10)
ax.set_xlim([0, 1000])
def formatnum(x, pos):
    return '$%.1f$x$10^{4}$' % (x/10000)
formatter = FuncFormatter(formatnum)
ax.yaxis.set_major_formatter(formatter)
ax.set_xlabel('Episode')
ax.set_ylabel('Waiting time')
plt.show()
  • 結果
    座標變成科學計數
  • 公式表示
A = np.random.randint(10000, 50000, size=(1000))
f, ax = plt.subplots(1, 1)
ax.scatter(range(len(A)), A , color='k', label='A', marker='o', s=10)
ax.set_xlim([0, 1000])
def formatnum(x, pos):
    return '$%.1f$x$10^{4}$' % (x/10000)
def formatnum_x(x, pos):
    return '$%.2f \pi$' % (x/500)
formatter1 = FuncFormatter(formatnum)
formatter2 = FuncFormatter(formatnum_x)
ax.yaxis.set_major_formatter(formatter1)
ax.xaxis.set_major_formatter(formatter2)
plt.show()
  • 結果
    沒描述