3

I would like to format my xtick and ytick values to two decimal places in float and also add a "%" at the end. How would I go about that?

x_sum = cm.sum(axis=0)*100
y_sum = cm.sum(axis=1)*100
plt.xticks(tick_marks, x_sum)
plt.yticks(tick_marks, y_sum)

Currently, the ticks give me long decimal values.

asked Jul 5, 2018 at 15:09

2 Answers 2

8

Seen from the question, you want to set the ticks manually anyways, so you just need to format the ticklabels,

import numpy as np
import matplotlib.pyplot as plt
cm = np.sort(np.random.rand(64)).reshape((8,8))
tick_marks=np.arange(8)
plt.imshow(cm)
x_sum = cm.sum(axis=0)*100
y_sum = cm.sum(axis=1)*100
fmt = lambda x: "{:.2f}%".format(x)
plt.xticks(tick_marks, [fmt(i) for i in x_sum], rotation=90)
plt.yticks(tick_marks, [fmt(i) for i in y_sum])
plt.tight_layout()
plt.show()

enter image description here

For automatic percentage labeling, the matplotlib.ticker.PercentFormatter makes sense:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
cm = np.sort(np.random.rand(64)).reshape((8,8))
plt.imshow(cm, extent=(0,80,0,80))
plt.gca().xaxis.set_major_formatter(PercentFormatter(decimals=2))
plt.gca().yaxis.set_major_formatter(PercentFormatter(decimals=2))
plt.gca().tick_params(axis="x",rotation=90)
plt.tight_layout()
plt.show()

enter image description here

answered Jul 5, 2018 at 17:55

Comments

4

A clean way to define the formatting of tick labels is to create your own tick formatter. This is possible by utilizing matplotlib's FuncFormatter.

from matplotlib.ticker import FuncFormatter
from matplotlib import pyplot as plt
def format_tick_labels(x, pos):
 return '{0:.2f}%'.format(x)
values = range(20)
f, ax = plt.subplots()
ax.xaxis.set_major_formatter(FuncFormatter(format_tick_labels))
ax.plot(values)

enter image description here

answered Jul 5, 2018 at 15:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.