简体   繁体   English

Matplotlib x标签用于对数图

[英]Matplotlib x-labels for logarithmic graph

I'm trying to plot some data in matplotlib to show the results of an experiement as follows: 我正在尝试在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]

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 但是,正如您所见,我的xlabels并没有出现,如下所示 Matplotlib轴图

If I remove the line ax.set_xticklabels(xvalues) then I get the following result, which isn't what I'd like either: 如果删除行ax.set_xticklabels(xvalues)则会得到以下结果,这也不是我想要的结果: Matplotlib第二轴图

I'd be very grateful for some help in plotting the correct values on the x-axis! 对于在X轴上绘制正确值的帮助,我将不胜感激!

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 产量

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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