首頁  >  文章  >  後端開發  >  如何控制Matplotlib中浮動刻度標籤的格式?

如何控制Matplotlib中浮動刻度標籤的格式?

Patricia Arquette
Patricia Arquette原創
2024-10-22 10:39:02683瀏覽

How to Control the Format of Float Tick Labels in Matplotlib?

指定浮動刻度標籤的格式

設定十進位數字

要在刻度標籤中使用特定的十進位格式,請使用 FormatStrFormatter 類別。此類別採用指定所需格式的字串作為參數。例如:

<code class="python">from matplotlib.ticker import FormatStrFormatter

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))</code>

在此範例中,格式字串「%.2f」指定刻度標籤應具有兩位小數。有關更多格式化選項,請參閱 Matplotlib 文件。

使用更精細的控制:ScalarFormatter

或者,將 ScalarFormatter 類別與 useOffset 和 useLocale 參數一起使用。 useOffset 禁用科學記數法,而 useLocale 使用系統的區域設定來決定格式樣式(例如,小數分隔符號、千位分隔符號)。

<code class="python">fig, ax = plt.subplots()
# Disable scientific notation
ax.yaxis.set_major_formatter(ScalarFormatter(useOffset=False, useLocale=False))
# Specify decimal places
ax.yaxis.set_major_locator(MultipleLocator(0.5))</code>

無小數位

完全刪除小數位,將格式字串設為「%d」。這將顯示沒有任何小數部分的整數:

<code class="python">from matplotlib.ticker import StrMethodFormatter

ax.yaxis.set_major_formatter(StrMethodFormatter('{x:.0f}'))</code>

以上是如何控制Matplotlib中浮動刻度標籤的格式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn