Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide y-ticks by a certain number in matplotlib?

I have a simple matplotlib histogram and I need to divide ylabels to a certain number. For example I have 100 200 and 300 while I need to have 1,2, and 3. Any suggestion?

Here is my code:

import numpy
import matplotlib
# Turn off DISPLAY
matplotlib.use('Agg')
import pylab

# Figure aspect ratio, font size, and quality
matplotlib.pyplot.figure(figsize=(100,50),dpi=400)
matplotlib.rcParams.update({'font.size': 150})

matplotlib.rcParams['xtick.major.pad']='68'
matplotlib.rcParams['ytick.major.pad']='68'


# Read data from file
data=pylab.loadtxt("data.txt")

# Plot a histogram
n, bins, patches = pylab.hist(data, 50, normed=False, histtype='bar')
#matplotlib.pyplot.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)

# Axis labels
pylab.xlabel('# of Occurence')
pylab.ylabel('Signal Probability')

# Save in PDF file
pylab.savefig("Output.pdf", dpi=400, bbox_inches='tight', pad_inches=1)
like image 202
Mojtaba Avatar asked Dec 26 '22 00:12

Mojtaba


1 Answers

It appears that you don't wish to alter the underlying data, and that this is simply a formatting issue. In that case you can use an instance of the formatter-function class found in the ticker module.

A formatter function -- for use with an instance of the formatter-function class -- takes two arguments: the tick-label and the tick-position, and returns the formatted tick-label. Below is one for your purpose:

def numfmt(x, pos): # your custom formatter function: divide by 100.0
    s = '{}'.format(x / 100.0)
    return s

import matplotlib.ticker as tkr     # has classes for tick-locating and -formatting
yfmt = tkr.FuncFormatter(numfmt)    # create your custom formatter function

# your existing code can be inserted here

pylab.gca().yaxis.set_major_formatter(yfmt)

# final step
pylab.savefig("Output.pdf", dpi=400, bbox_inches='tight', pad_inches=1)
like image 186
mechanical_meat Avatar answered Dec 31 '22 13:12

mechanical_meat