removing leading 0 from matplotlib tick label formatting

2024/11/16 18:32:06

How can I change the ticklabels of numeric decimal data (say between 0 and 1) to be "0", ".1", ".2" rather than "0.0", "0.1", "0.2" in matplotlib? For example,

hist(rand(100))
xticks([0, .2, .4, .6, .8])

will format the labels as "0.0", "0.2", etc. I know that this gets rid of the leading "0" from "0.0" and the trailing "0" on "1.0":

from matplotlib.ticker import FormatStrFormatter
majorFormatter = FormatStrFormatter('%g')
myaxis.xaxis.set_major_formatter(majorFormatter) 

That's a good start, but I also want to get rid of the "0" prefix on "0.2" and "0.4", etc. How can this be done?

Answer

Although I am not sure it is the best way, you can use a matplotlib.ticker.FuncFormatter to do this. For example, define the following function.

def my_formatter(x, pos):"""Format 1 as 1, 0 as 0, and all values whose absolute values is between0 and 1 without the leading "0." (e.g., 0.7 is formatted as .7 and -0.4 isformatted as -.4)."""val_str = '{:g}'.format(x)if np.abs(x) > 0 and np.abs(x) < 1:return val_str.replace("0", "", 1)else:return val_str

Now, you can use majorFormatter = FuncFormatter(my_formatter) to replace the majorFormatter in the question.

Complete example

Let's look at a complete example.

from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as npdef my_formatter(x, pos):"""Format 1 as 1, 0 as 0, and all values whose absolute values is between0 and 1 without the leading "0." (e.g., 0.7 is formatted as .7 and -0.4 isformatted as -.4)."""val_str = '{:g}'.format(x)if np.abs(x) > 0 and np.abs(x) < 1:return val_str.replace("0", "", 1)else:return val_str# Generate some data.
np.random.seed(1) # So you can reproduce these results.
vals = np.random.rand((1000))# Set up the formatter.
major_formatter = FuncFormatter(my_formatter)plt.hist(vals, bins=100)
ax = plt.subplot(111)
ax.xaxis.set_major_formatter(major_formatter)
plt.show()

Running this code generates the following histogram.

Histogram with modified tick labels.

Notice the tick labels satisfy the conditions requested in the question.

https://en.xdnf.cn/q/71637.html

Related Q&A

How do I check if an iterator is actually an iterator container?

I have a dummy example of an iterator container below (the real one reads a file too large to fit in memory):class DummyIterator:def __init__(self, max_value):self.max_value = max_valuedef __iter__(sel…

Python Terminated Thread Cannot Restart

I have a thread that gets executed when some action occurs. Given the logic of the program, the thread cannot possibly be started while another instance of it is still running. Yet when I call it a sec…

TypeError: NoneType object is not subscriptable [duplicate]

This question already has an answer here:mysqldb .. NoneType object is not subscriptable(1 answer)Closed 8 years ago.The error: names = curfetchone()[0]TypeError: NoneType object is not subscriptable. …

Where can I find numpy.where() source code? [duplicate]

This question already has answers here:How do I use numpy.where()? What should I pass, and what does the result mean? [closed](2 answers)Closed 4 years ago.I have already found the source for the num…

NSUserNotificationCenter.defaultUserNotificationCenter() returns None in python

I am trying to connect to the Mountain Lion notification center via python. Ive installed pyobjc and am following the instructions here and here. Also see: Working with Mountain Lions Notification Cent…

Flask app hangs while processing the request

I have a simple flask app, single page, upload html and then do some processing on it on the POST; at POST request; i am using beautifulsoup, pandas and usually it takes 5-10 sec to complete the task. …

How do I make a server listen on multiple ports

I would like to listen on 100 different TCP port with the same server. Heres what Im currently doing:-import socket import selectdef main():server_socket = socket.socket(socket.AF_INET, socket.SOCK_STR…

Django REST Framework: return 404 (not 400) on POST if related field does not exist?

Im developing a REST API which takes POST requests from some really brain-dead software which cant PATCH or anything else. The POSTs are to update Model objects which already exist in the database.Spec…

How can i login in instagram with python requests?

Hello i am trying to login instagram with python requests library but when i try, instagram turns me "bad requests". İs anyone know how can i solve this problem?i searched to find a solve f…

How to abstract away command code in custom django commands

Im writing custom django commands under my apps management/commands directory. At the moment I have 6 different files in that directory. Each file has a different command that solves a unique need. How…