Home > Enterprise >  How can I change the display of the values on the x-axis in matplotlib?
How can I change the display of the values on the x-axis in matplotlib?

Time:09-29

To make it more readable on the graph, I would like to remove the decimals from the values of x from 0.1 to 20 and put the values from 0 to 0.09 in power. So that there is no more 0.10 displayed but 0.1, no more 2.00 but simply 2 and no more 0.01 but 10e-2 for example.

Do you have any idea how to do it?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

x = sorted([0.09, 20, 0.6, 6, 0.05, 0.5, 0.4, 4, 0.3, 3, 2, 0.1, 0.2,
            0.9, 0.8, 10, 0.7, 1, 0.08, 0.07, 0.06, 0.04, 0.03, 0.02, 0.01, 0.005])
y = list(np.arange(0.0, 2.6, 0.1))

plt.plot(x, y)
plt.xscale('log', base=10)
ax = plt.gca()
ax.xaxis.set_major_formatter(ScalarFormatter())
ax.set_xticks(x)
plt.xticks(fontsize=6)
plt.grid()
plt.show()

enter image description here

CodePudding user response:

You can take advantage of labels in plt.xticks() function. This way -

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

fig = plt.figure(figsize=(10, 7))

x = sorted([0.09, 20, 0.6, 6, 0.05, 0.5, 0.4, 4, 0.3, 3, 2, 0.1, 0.2,
            0.9, 0.8, 10, 0.7, 1, 0.08, 0.07, 0.06, 0.04, 0.03, 0.02, 0.01, 0.005])
y = list(np.arange(0.0, 2.6, 0.1))

plt.plot(x, y)
plt.xscale('log')
ax = plt.gca()
ax.xaxis.set_major_formatter(ScalarFormatter())
plt.xticks(ticks=x, labels=[str(el) for el in x], fontsize=6)
plt.grid()
plt.show()

Output looks like this -

Plot

  • Related