1

I want to format the y-axis of my histogram with the function:

def convertCountToKm2(x):
    return x * 25.0 * 1e-6

Because this converts the histogram y-axis from a cell count to an area in km2. The histogram is created by:

bins = numpy.array(list(range(0,7000,1000)))
plt.hist(Anonzero,bins)

Which results in this figure:

enter image description here

I have tried calling the function with the following code:

yFormat = tkr.FuncFormatter(convertCountToKm2)
plt.yaxis.set_major_formatter(yFormat)

which returns an error: module 'matplotlib.pyplot' has no attribute 'yaxis'

How do I format axis number format to thousands with a comma in matplotlib? seems too have some hints about formatting the axis, but that is not specific for this case. I am unable to use it to answer my question.

LMB
  • 384
  • 2
  • 6
  • 18

1 Answers1

3

The error tells you that plt (which I suppose is pyplot) has no yaxis, which is correct. yaxis is an attribute of the axes. Use

plt.gca().yaxis.set_major_formatter(...)

Solving this you might run into another problem, that is that functions for the FuncFormatter need to accept two arguments, x, pos. You may ignore pos, but it has to be in the signature

def convertCountToKm2(x, pos=None):
    return x * 25.0 * 1e-6

yFormat = FuncFormatter(convertCountToKm2)
plt.gca().yaxis.set_major_formatter(yFormat)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712