Seaborn 圖中的反向對數標度

Manav Narula 2024年2月15日 Seaborn Seaborn Tick
Seaborn 圖中的反向對數標度

Python 配備了不同的函式來處理對數和指數值。我們使用 numpy 和 math 模組提供的 log()exp() 函式來計算這些值。

例如,

print(np.log(50))
print(np.exp(3.912023005428146))

輸出:

3.912023005428146
49.99999999999999

上述兩個函式的許多更改使我們能夠計算具有不同基數和更多基數的對數。指數值被視為逆對數或反向對數值。

也可以在圖形和繪圖上處理這些值。seaborn 模組基於 matplotlib 模組,用於視覺化目的,可以建立許多不同型別的圖形。我們可以使用不同的函式根據我們的要求調整最終數字。

在本教程中,我們將學習在 Python 中反轉 seaborn 圖上的對數值。

在我們的示例中,我們將使用 log 函式來計算所需的值,並使用 seaborn 模組的 violinplot() 函式繪製它們。

看下面的程式碼,

import seaborn as sns
import numpy as np

lst = [1, 5, 8, 9, 5, 2, 5, 6, 9]

pl = sns.violinplot(y=np.log(lst))

seaborn 日誌圖

我們可以使用 set_yticklabels()set_xticklabels() 函式在兩個軸上自定義標籤刻度值。我們將使用具有上述功能的反向日誌功能來設定刻度標籤值。

例如,

import seaborn as sns
import numpy as np

lst = [1, 5, 8, 9, 5, 2, 5, 6, 9]

pl = sns.violinplot(y=np.log(lst))
pl.set_yticklabels([f"{np.expm1(l):.2f}" for l in pl.get_yticks()])

seaborn 圖中的反向對數刻度

get_yticks() 函式返回預設標籤,我們使用 exp() 函式計算它們的反向日誌。我們使用 Python 中用於字串格式化的 fstrings 將最終結果格式化為僅兩位小數。

通過這種方式,我們通過計算列表元素的對數值並使用反向對數函式在刻度標籤上提及原始值來建立小提琴圖。

請注意,我們在示例中使用了 numpy 模組中的函式,而不是 math 模組。這是因為 numpy log()exp() 函式也可以直接計算列表或陣列的所需值。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

相關文章 - Seaborn Tick