簡體   English   中英

Matplotlib x標簽用於對數圖

[英]Matplotlib x-labels for logarithmic graph

我正在嘗試在matplotlib中繪制一些數據以顯示實驗的結果,如下所示:

xvalues = [2, 4, 8, 16, 32, 64, 128, 256]
yvalues = [400139397.517, 339303459.4277, 296846508.2103, 271801897.1163,
           295153640.7553, 323820220.6226, 372099806.9102, 466940449.0719]

我希望以對數比例繪制此圖,以使其更容易可視化,因此編寫了以下代碼:

import matplotlib.pyplot as plt

def plot_energy(xvalues, yvalues):
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)

    ax.scatter(xvalues, yvalues)
    ax.plot(xvalues, yvalues)

    ax.set_xscale('log')

    ax.set_xticklabels(xvalues)

    ax.set_xlabel('RUU size')
    ax.set_title("Energy consumption")
    ax.set_ylabel('Energy per instruction (nJ)')
    plt.show()

但是,正如您所見,我的xlabels並沒有出現,如下所示 Matplotlib軸圖

如果刪除行ax.set_xticklabels(xvalues)則會得到以下結果,這也不是我想要的結果: Matplotlib第二軸圖

對於在X軸上繪制正確值的幫助,我將不勝感激!

提前致謝。

您僅更改刻度線的標簽,而不更改刻度線的位置。 如果您使用:

ax.set_xticks(xvalues)

看起來像:

在此處輸入圖片說明

大多數時候,如果您想要完全不同的東西(例如類別標簽),則只想設置(覆蓋)標簽。 如果要堅持使用軸上的實際單位,最好使用自定義格式化程序設置刻度位置。

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

def plot_energy(xvalues, yvalues):
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)

    ax.scatter(xvalues, yvalues)
    ax.semilogx(xvalues, yvalues, basex = 2)
    ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
    ax.set_xlabel('RUU size')
    ax.set_title("Energy consumption")
    ax.set_ylabel('Energy per instruction (nJ)')
    plt.show()

xvalues = [2, 4, 8, 16, 32, 64, 128, 256]
yvalues = [400139397.517, 339303459.4277, 296846508.2103, 271801897.1163,
           295153640.7553, 323820220.6226, 372099806.9102, 466940449.0719]
plot_energy(xvalues, yvalues)

產量

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM