为刻度标签指定浮点数格式

新手上路,请多包涵

我正在尝试在 matplotlib 子图环境中将格式设置为两位十进制数。不幸的是,我不知道如何解决这个任务。

为了防止在 y 轴上使用科学记数法,我使用了 ScalarFormatter(useOffset=False) 正如您在下面的代码片段中所见。我认为我的任务应该通过将更多选项/参数传递给使用的格式化程序来解决。但是,我在 matplotlib 的文档中找不到任何提示。

如何设置两位十进制数字或不设置(两种情况都需要)?不幸的是,我无法提供样本数据。


-- 片段 –

 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)

原文由 albert 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 329
2 个回答

一般具体 请参阅相关文档

from matplotlib.ticker import FormatStrFormatter

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

在此处输入图像描述

原文由 tacaswell 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你直接使用 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

文档 中:

类 matplotlib.ticker.StrMethodFormatter(fmt)

使用新式格式字符串(如 str.format() 使用的那样)来格式化刻度。

用于值的字段必须标记为 x,用于位置的字段必须标记为 pos。

原文由 CodeWarrior 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题