Home > OS >  How to control significant digits of axis ticks for python plot
How to control significant digits of axis ticks for python plot

Time:08-02

stack overflow. I am making a python histogram where I want to control the significant digits of my x or y ticks for any generalized data set. For example, instead of the y axis saying 80%, I want to make it 80.0% or 80.00%. Is there a generalized solution for this such that I can apply it to any data set?

import random
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from matplotlib.ticker import PercentFormatter
data = [9.3, 7,8, 2.3, 0.001, 19.3]
fig, ax = plt.subplots()
CO = len(data[:])
y = data[:]
ax.set_xlim(0,34)
sns.histplot(y, bins=int(np.sqrt(CO)), stat='percent')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.axvline(x = np.median(data[:]), color = 'r')
plt.gca().yaxis.set_major_formatter(PercentFormatter(100))

CodePudding user response:

Add this code

from matplotlib import ticker as mtick

fmt = '%.2f%%'  # as per no of zero(or other) you want after decimal point
yticks = mtick.FormatStrFormatter(fmt)
plt.gca().yaxis.set_major_formatter(yticks)

Read this:

  1. Pyplot: using percentage on x axis
  2. Format y axis as percent
  • Related