Jiří Polcar
Jiří Polcar

Reputation: 1222

How to specify ticks formatter for several subplots

I need to specify ticks formatter for each plot of several subplots:

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker


x = np.arange(10)
y = x

fig = plt.figure()

for i in [1, 2, 3]:
    ax = fig.add_subplot(3, 1, i)
    ax.plot(x, y)
    ticks = ticker.FuncFormatter(lambda x, pos: '{}:{:g}'.format(i, x))
    ax.xaxis.set_major_formatter(ticks)

plt.show()

But only the last (bottom) fotmatter is used for all other plots. What I do wrong? output example

Upvotes: 3

Views: 2689

Answers (1)

Ffisegydd
Ffisegydd

Reputation: 53678

You can use a ticker.FormatStrFormatter object as shown below.

I believe the problem with your original approach was that you were setting the Formatter for each axis to the tick variable and then overwriting it on the next iteration, as such all your graphs were using the tick variable from the last iteration.

When you create Formatter objects you have to have one for each subplot, in my code below it's not a problem because I don't assign the FormatStrFormatter to a variable.

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker

x = np.arange(10)
y = x

fig, axes = plt.subplots(nrows=3, ncols=1)

for i, ax in enumerate(axes):
    ax.plot(x, y)
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('{}:%d'.format(i+1)))

plt.show()

Example plot

EDIT

Here is a version which uses the original FuncFormatter formatter object. The map method creates three separate ticker objects from their associated lambda functions. The for loop iterates over both ax and tick to assign each subplot.

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker

x = np.arange(10)
y = x

fig, axes = plt.subplots(nrows=3, ncols=1)

def create_ticker(i):
    # Create a FuncFormatter.
    return ticker.FuncFormatter(lambda x, pos: '{}:{:g}'.format(i+1, x))

ticks = map(create_ticker, range(3))

for ax, tick in zip(axes, ticks):
    ax.plot(x, y)
    ax.xaxis.set_major_formatter(tick)

plt.show()

Upvotes: 2

Related Questions