Python Matplotlib:指定刻度标签的浮点数格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29188757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib: Specify format of floats for tick labels
提问by albert
I am trying to set the format to two decimal numbers in a matplotlib subplot environment. Unfortunately, I do not have any idea how to solve this task.
我试图在 matplotlib 子图环境中将格式设置为两个十进制数。不幸的是,我不知道如何解决这个任务。
To prevent using scientific notation on the y-axis I used ScalarFormatter(useOffset=False)
as you can see in my snippet below. I think my task should be solved by passing further options/arguments to the used formatter. However, I could not find any hint in matplotlib's documentation.
为了防止在 y 轴上使用科学记数法,我使用了ScalarFormatter(useOffset=False)
以下代码片段。我认为我的任务应该通过将更多选项/参数传递给使用的格式化程序来解决。但是,我在 matplotlib 的文档中找不到任何提示。
How can I set two decimal digits or none (both cases are needed)? I am not able to provide sample data, unfortunately.
如何设置两位十进制数字或无(两种情况都需要)?不幸的是,我无法提供示例数据。
-- SNIPPET --
-- 片段 --
f, axarr = plt.subplots(3, sharex=True)
data = conv_air
x = range(0, len(data))
axarr[0].scatter(x, data)
axarr[0].set_ylabel('$T_\mathrm{air,2,2}$', size=FONT_SIZE)
axarr[0].yaxis.set_major_locator(MaxNLocator(5))
axarr[0].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[0].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[0].grid(which='major', alpha=0.5)
axarr[0].grid(which='minor', alpha=0.2)
data = conv_dryer
x = range(0, len(data))
axarr[1].scatter(x, data)
axarr[1].set_ylabel('$T_\mathrm{dryer,2,2}$', size=FONT_SIZE)
axarr[1].yaxis.set_major_locator(MaxNLocator(5))
axarr[1].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[1].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[1].grid(which='major', alpha=0.5)
axarr[1].grid(which='minor', alpha=0.2)
data = conv_lambda
x = range(0, len(data))
axarr[2].scatter(x, data)
axarr[2].set_xlabel('Iterationsschritte', size=FONT_SIZE)
axarr[2].xaxis.set_major_locator(MaxNLocator(integer=True))
axarr[2].set_ylabel('$\lambda$', size=FONT_SIZE)
axarr[2].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[2].yaxis.set_major_locator(MaxNLocator(5))
axarr[2].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[2].grid(which='major', alpha=0.5)
axarr[2].grid(which='minor', alpha=0.2)
采纳答案by tacaswell
See the relevant documentation in generaland specifically
from matplotlib.ticker import FormatStrFormatter
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
回答by sapo_cosmico
The answer above is probably the correct way to do it, but didn't work for me.
上面的答案可能是正确的方法,但对我不起作用。
The hacky way that solved it for me was the following:
为我解决它的hacky方法如下:
ax = <whatever your plot is>
# get the current labels
labels = [item.get_text() for item in ax.get_xticklabels()]
# Beat them into submission and set them back again
ax.set_xticklabels([str(round(float(label), 2)) for label in labels])
# Show the plot, and go home to family
plt.show()
回答by CodeWarrior
If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:
如果你直接使用 matplotlib 的 pyplot (plt) 并且你对新式格式字符串比较熟悉,你可以试试这个:
from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places
From the documentation:
从文档:
class matplotlib.ticker.StrMethodFormatter(fmt)
Use a new-style format string (as used by str.format()) to format the tick.
The field used for the value must be labeled x and the field used for the position must be labeled pos.
类 matplotlib.ticker.StrMethodFormatter(fmt)
使用新样式的格式字符串(如 str.format() 使用的那样)来格式化刻度线。
用于值的字段必须标记为 x,用于位置的字段必须标记为 pos。
回答by foxpal
In matplotlib 3.1, you can also use ticklabel_format. To prevents scientific notation without offsets:
在 matplotlib 3.1 中,您还可以使用ticklabel_format。防止没有偏移的科学记数法:
plt.gca().ticklabel_format(axis='both', style='plain', useOffset=False)