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
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()
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()
answered Jul 5, 2018 at 17:55
ImportanceOfBeingErnest ImportanceOfBeingErnest
342k60 gold badges735 silver badges770 bronze badges
Comments
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)
answered Jul 5, 2018 at 15:29
Comments
lang-py