livia
livia

Reputation: 1

Decimal formatting ticks on Matplotlib

I have a plot but the ticks are like this: 0.200558, 0.202004

0.200 0.202



I wanted someting like: 0.200, 0.202, 0.204

I tried

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

but that's what I got: 0, 5.000, 10.000

0 5 10

Upvotes: 0

Views: 1258

Answers (1)

pawjast
pawjast

Reputation: 21

I usually find it easier to generate the ticks with np.arange and the set the correct formatting using f-strings and list comprehension. It's important to set the ticks first, and then set the tick labels.

See the example below:

import matplotlib.pyplot as plt
import numpy as np

# Generate 10 random points between 0 and 1
data = np.random.random(10)

# Plot the data
fig, ax = plt.subplots(
    figsize=(10,8)
)
ax.plot(data)

# Generate and format the ticks
y_ticks = np.arange(0,1, 0.123)
ax.set_ylim(y_ticks[0], y_ticks[-1])
ax.set_yticks(y_ticks)
ax.set_yticklabels(
    [f"{label:.3f}" for label in y_ticks]
);

This is what you'll get.

Upvotes: 1

Related Questions