【问题标题】:x.x format scientific style y-ticks matplotlibx.x 格式科学风格 y-ticks matplotlib
【发布时间】:2019-03-27 10:14:35
【问题描述】:

我正在使用 matplotlib 创建一些图。

对于我使用style='sci'scilimits=(0,0) 的情节

代码如下:

for key in urbs_values.keys():
    # y-Axis (values)
    u[key] = np.array(urbs_values[key])
    o[key] = np.array(oemof_values[key])

    # draw plots
    plt.plot(i, u[key], label='urbs_'+str(key), linestyle='None', marker='x')
    plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
    plt.plot(i, o[key], label='oemof_'+str(key), linestyle='None', marker='.')
    plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))

这通常是一致的,但有时我会在 y 轴上以 x.x 的格式获取值,有时我会得到 x.xx,但我并不觉得它很优雅。

有没有办法通过动态缩放科学符号来强制 matplotlib 以 x.x 等格式始终为我提供 y 值?

这是一个我不喜欢的示例情节:

【问题讨论】:

  • 您应该在整个问题中将“逗号”一词替换为“十进制”,因为它不是逗号,可能会让人感到困惑
  • @Bazingaa 完成。
  • @DavidG 并不是因为我不想将 y 值更改为整数。
  • 哦,我现在明白了。它比我想象的要复杂一些。我会撤回欺骗投票

标签: python matplotlib


【解决方案1】:

您可以根据数据中的最大值动态设置限制:

def grabMaxExponent(values, precision=1):
    """Given a list of numericals, returns the exponent of the max
    value in scientific notation, adjusted to have no sig figs in
    decimal places.

    e.g. 190 > 1.9E+02 > 19E+01
    returns exponent (1)"""

    # Grab max value and convert to scientific notation
    value = format(max(values), f"5.{precision}E")

    # Pull exponent
    a,m = value.split('E+')
    a,b = a.split('.')
    a,b,m = map(int, (a,b,m))

    # If significant figures non-zero, increase exponent to bring them before decimal point
    if b > 0:
        m-=precision

    return m

m = grabMaxExponent(y)

# Set scilimits to m
plt.ticklabel_format(axis='y', style='sci', scilimits=(m,m))

https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.ticklabel_format.html

【讨论】:

  • 很快就会检查 :) ty
  • aight 我检查了它,但它也不一致,所以我改变了问题。对于那个很抱歉。你的答案是有时在 y 轴上用 4 位数字创建整数,有时用 1 或 2 等...
  • @oakca 输出的位数取决于您的数据以及您将precision 的值设置为什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2021-10-08
相关资源
最近更新 更多