简体   繁体   中英

Matplotlib x-labels for logarithmic graph

I'm trying to plot some data in matplotlib to show the results of an experiement as follows:

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]

I wish to plot this on a logarithmic scale to make it easier to visualise and so have written the following code:

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()

However as you can see my xlabels don't appear as I'd like them to as seen below Matplotlib轴图

If I remove the line ax.set_xticklabels(xvalues) then I get the following result, which isn't what I'd like either: Matplotlib第二轴图

I'd be very grateful for some help in plotting the correct values on the x-axis!

Thanks in advance.

You are only altering the labels of the ticks, not the ticks position. If you use:

ax.set_xticks(xvalues)

It looks like:

在此处输入图片说明

Most of the time you only want to set (override) the labels if you want something completely different like category labels. If you want to stick with the actual units on the axis, its better to set the tick positions with (if needed) a custom formatter.

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)

yields

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM