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

Patricia Arquette
發布: 2024-10-22 10:39:02
原創
682 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!