Search code examples
pythonmatplotlibscipymode

How to return just the mode using SciPy


I am trying to display the mode of a population on a graph, but I am not able to. I can calculate mode:

    stats.mode(rec)

which returns:

    mode: ModeResult(mode=array([0.784]), count=array([8]))

but when I go to graph it with:

   plt.text(0.70, 14, r'Mode = {0:.2f}'.format(stats.mode(rec)))

I can't display it because SciPy has gien too many variables to display ~just~ the mode

Can I get SciPy to give me just the mode (ie 0.784, in this case), without having to do it manually?


Solution

  • The issue is that the return value is a ModeResult object. If you inspect this object with dir(mode), then you can get a list of its attributes. In this case, you want the mode attribute, which as you can see is actually an array, so here's my suggestion:

    mode = stats.mode(rec).mode[0]
    plt.text(0.70, 14, r'Mode = {0:.2f}'.format(mode))