1

For a semilogy matplotlib plot, I would like to have only y axis ticks values with decimal notation (like: 0.4, 10 etc.) but no scientific values (like 4e-1, 1e2 etc.).

The solution shown in Matplotlib log scale tick label number formatting and also depicted below, does not work properly, when the axis tick values are not tens potency values:

y axis tick labels have exponential description

How do I have to change the code that the y axis tick labels descriptions are [0.01, 0.02, 0.03, and 0.04]?

Or is there nowadays a matplotlib function that does this automatically?

import pandas as pd
import numpy as np

df = pd.DataFrame({'a': [1, 2], 'b': [0.04, 0.007]})

import matplotlib

matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
from matplotlib import ticker

ax = plt.subplot(1, 1, 1)
ax.semilogy(df.set_index('a').b, 'o', markersize=2)


def myLogFormat(y, pos):
    # Find the number of decimal places required
    decimalplaces = int(np.maximum(-np.log10(y), 0))  # =0 for numbers >=1
    # Insert that number into a format string
    formatstring = '{{:.{:1d}f}}'.format(decimalplaces)
    # Return the formatted tick label
    return formatstring.format(y)


ax.yaxis.set_major_formatter(ticker.FuncFormatter(myLogFormat))
# ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, _: '{:g}'.format(y)))
plt.grid()
plt.show()
user7468395
  • 1,299
  • 2
  • 10
  • 23

1 Answers1

2

You can use the following solution as shown in this answer

from matplotlib import ticker

ax = plt.subplot(1, 1, 1)
ax.semilogy(df.set_index('a').b, 'o', markersize=2)

ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.3f'))
ax.yaxis.set_minor_formatter(ticker.FormatStrFormatter('%.3f'))

plt.grid()
plt.show()

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71