在Matplotlib中以科学计数法显示第一个十进制数字 [英] Displaying first decimal digit in scientific notation in Matplotlib

查看:31
本文介绍了在Matplotlib中以科学计数法显示第一个十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在生成带有科学符号的y轴不同的图形,这些图形在某些情节上导致像2或6的刻度,而在另一些情节上则是2.5或8.9的刻度.我希望始终在y轴上带有一个带有十进制小数点的刻度,即使它添加了零也是如此.这是一个例子

I am currently generating different figures with a scientific notation for the y-axis leading to ticks like 2 or 6 on some plots, but 2.5 or 8.9 on some others. I would like to always have ticks with one decimal on the y-axis, even if it adds a zero. Here is an example

import matplotlib.pyplot as plt
import numpy as np

plt.plot(np.arange(1, 10), np.arange(1, 10)**5)
ax = plt.gca()
plt.ticklabel_format(axis='y', style='sci')
ax.yaxis.major.formatter.set_powerlimits((0,0))
plt.show()

我可以添加什么来强制在 y 轴上绘制刻度 1.0、2.0 等 ?

What could I add to force to plot ticks 1.0, 2.0, etc. on the y-axis?

推荐答案

ScalarFormatter 当前不支持刻度的自定义格式,例如设置小数位数.但是,您可以扩展该类,以便强制它使用您指定的格式.这是一个示例:

The ScalarFormatter does not currently support custom formats for the ticks, such as setting numbers of decimals. However you can extend the class, so to force it to use a format that you specify. Here is an example:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

class ScalarFormatterForceFormat(ScalarFormatter):
    def _set_format(self):  # Override function that finds format to use.
        self.format = "%1.1f"  # Give format here

plt.plot(np.arange(1, 10), np.arange(1, 10)**5)
ax = plt.gca()
yfmt = ScalarFormatterForceFormat()
yfmt.set_powerlimits((0,0))
gca().yaxis.set_major_formatter(yfmt)
plt.show()

这是它的外观.

这篇关于在Matplotlib中以科学计数法显示第一个十进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆