3

I create a plot using matplotlib which has large number on the y-axis. I would like to add a thousand separator on this axis. This separator should be a quote and not a comma. So I would like to plot something like 10'000 for the number 10000.

If I use a comma for a thousand separator, I know about:

ax = plt.gca()
fmt = "{x:,.0f}"
tick = mpl.ticker.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)

but it does not work for single quote ('). What should I do?

Dvg25
  • 98
  • 7
  • 1
    Relevant: https://stackoverflow.com/questions/16670125/python-format-string-thousand-separator-with-spaces Thousands separators other than comma are not natively supported. See https://docs.python.org/3.4/whatsnew/3.1.html#pep-378-format-specifier-for-thousands-separator You can always use a `FuncFormatter` instead and supply a function that replaces comma by any other character. – ImportanceOfBeingErnest Mar 05 '19 at 13:17
  • 1
    This can be adapted to get a quote as the separator https://stackoverflow.com/questions/25973581/how-do-i-format-axis-number-format-to-thousands-with-a-comma-in-matplotlib/25974179#25974179 – DavidG Mar 05 '19 at 13:20

1 Answers1

1

It can be done with custom function. Can be adapted if "ax" is used instead of "plt" to reference figure. Function takes in y axis value as float, converts it to string and loops from end of string and adds ' after every third character. Wont work without pos variable, as 2 arguments are passed.

enter image description here

    def format_string(x, pos):
        tick_str = ""
        x = str(int(x))
        count = 1
        for i in range(len(x), -1, -1):
            if count % 3 == 0 and len(x) > 3 and (i-1) != 0 and (i-1) != -1:
                tick_str = "'" + x[i-1] + tick_str
            elif (i-1) != -1:
                tick_str = x[i-1] + tick_str
            count = count + 1

        return tick_str

    plt.gca().get_yaxis().set_major_formatter(plt.FuncFormatter(format_string))
Matiss Zuravlevs
  • 329
  • 2
  • 11