Home > Software design >  How to add measured input values as x-axis labels in generated chart?
How to add measured input values as x-axis labels in generated chart?

Time:10-07

I'm using perfplot to make only a few measurements. I would like to see measured input values as x-axis labels similarly to generated y-axis labels.

Currently I see 10^2 10^3 10^4 10^5 10^6 10^7 as x-axis labels.

I want to have 16 512 16384 524288 16777216 as x-axis labels.

perfplot uses internally matplotlib, so I think it should be possible to achieve.

Example code:

import numpy as np
import perfplot

perfplot.show(
    setup=lambda n: np.random.rand(n),
    kernels=[
        lambda a: np.c_[a, a],
        lambda a: np.stack([a, a]).T,
        lambda a: np.vstack([a, a]).T,
        lambda a: np.column_stack([a, a]),
        lambda a: np.concatenate([a[:, None], a[:, None]], axis=1),
    ],
    labels=["c_", "stack", "vstack", "column_stack", "concat"],
    n_range=[16, 512, 16384, 524288, 16777216],
    xlabel="len(a)",
)

Current output:

enter image description here

CodePudding user response:

You can use plot instead of show to get access to the current axes object after perfplot has finished and then set ticks as needed:

import numpy as np
import perfplot
import matplotlib.pyplot as plt
import matplotlib.ticker as mt

n_range = [16, 512, 16384, 524288, 16777216]

perfplot.plot(
    setup=lambda n: np.random.rand(n),
    kernels=[
        lambda a: np.c_[a, a],
        lambda a: np.stack([a, a]).T,
        lambda a: np.vstack([a, a]).T,
        lambda a: np.column_stack([a, a]),
        lambda a: np.concatenate([a[:, None], a[:, None]], axis=1),
    ],
    labels=["c_", "stack", "vstack", "column_stack", "concat"],
    n_range=n_range,
    xlabel="len(a)",
)

ax = plt.gca()
ax.xaxis.set_ticks(n_range)
ax.xaxis.set_major_formatter(mt.StrMethodFormatter('{x}'))
plt.show()

enter image description here

  • Related