Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the formatters to make custom ticks in matplotlib?

How can I use the default tickformatters (which I like and don't want to have to recreate) to make my own custom tickmarks? The problem I am trying to solve is that I'd like to apply a function to all of the numbers on the y-axis.

For instance, let's say that I wanted to square all of the y-axis tick labels. I don't want to change their positions or change the underlying data, I just want to change the labels. I understand that I could write my own formatter from scratch, but I'd prefer to just write a wrapper around the existing formatters. I tried:

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

def my_formatter(x,pos):
     return ScalarFormatter(x**2,pos)
    
x = np.arange(10)
y = x
fig, ax = plt.subplots()
plt.plot(x,y)
ax.yaxis.set_major_formatter(plt.FuncFormatter(my_formatter))
plt.show()

But that doesn't work: enter image description here

I understand why it doesn't work, I'm trying to figure out how to actually call the ScalarFormatter so that I can get the strings it would generate.

like image 727
Jason Wright Avatar asked Oct 21 '25 13:10

Jason Wright


2 Answers

Use mpl.ticker.FuncFormatter which allows you to modify the value of your ticks (not the position) with a function.

I prefer to decorate the formatter like so:

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

@FuncFormatter
def my_formatter(x, pos):
     return "{}".format(x ** 2)
    
x = np.arange(10)
y = x
fig, ax = plt.subplots()
ax.plot(x, y)

# As we decorated the function we can just use 
#   the function name as the formatter argument

ax.yaxis.set_major_formatter(my_formatter)
plt.show()

You should return a string from your formatter and matplotlib will handle the positioning.

enter image description here

like image 76
Alex Avatar answered Oct 23 '25 03:10

Alex


I think you can try setting: ax.set_xticklabels() instead of having to define a function to pass it in.

Define your labels:

labels = x**2  # x is a np.array
ax.set_yticklabels(labels)
like image 37
astrochun Avatar answered Oct 23 '25 03:10

astrochun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!