Matplotlib Ticker

旧街凉风 提交于 2019-12-08 01:10:30

问题


Can someone give me an example of how to use the following tickFormatters. The docs are uninformative to me.

ticker.StrMethodFormatter() ticker.IndexFormatter()

for example I might think that

x = np.array([ 316566.962,  294789.545,  490032.382,  681004.044,  753757.024,
            385283.153,  651498.538,  937628.225,  199561.358,  601465.455])
y = np.array([ 208.075,  262.099,  550.066,  633.525,  612.804,  884.785,
            862.219,  349.805,  279.964,  500.612])
money_formatter = tkr.StrMethodFormatter('${:,}')

plt.scatter(x,y)
ax = plt.gca()
fmtr = ticker.StrMethodFormatter('${:,}')
ax.xaxis.set_major_formatter(fmtr)

would set my tick labels to be dollar signed and comma sep for thousands places ala

['$300,000', '$400,000', '$500,000', '$600,000', '$700,000', '$800,000', '$900,000']

but instead I get an index error.

IndexError: tuple index out of range

For IndexFormatter docs say:

Set the strings from a list of labels

don't really know what this means and when I try to use it my tics disappear.


回答1:


The StrMethodFormatter works indeed by supplying a string that can be formatted using the format method. So the approach of using '${:,}' goes in the right direction.

However from the documentation we learn

The field used for the value must be labeled x and the field used for the position must be labeled pos.

This means that you need to give an actual label x to the field. Additionally you may want to specify the number format as g not to have the decimal point.

fmtr = matplotlib.ticker.StrMethodFormatter('${x:,g}')

The IndexFormatter is of little use here. As you found out, you would need to provide a list of labels. Those labels are used for the index, starting at 0. So using this formatter would require to have the x axis start at zero and ranging over some whole numbers.

Example:

plt.scatter(range(len(y)),y)
fmtr = matplotlib.ticker.IndexFormatter(list("ABCDEFGHIJ"))
ax.xaxis.set_major_formatter(fmtr)

Here, the ticks are placed at (0,2,4,6,....) and the respective letters from the list (A, C, E, G, I, ...) are used as labels.



来源:https://stackoverflow.com/questions/44187290/matplotlib-ticker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!