【问题标题】:Adding + sign to exponent in matplotlib axes在 matplotlib 轴中向指数添加 + 号
【发布时间】:2016-05-26 17:46:09
【问题描述】:

我有一个对数图,范围从10^-310^+3。我希望值≥10^0 在指数中有一个+ 符号,类似于值<10^0 在指数中有一个- 符号。在 matplotlib 中是否有一种简单的方法可以做到这一点?

我查看了FuncFormatter,但实现这一点似乎过于复杂,而且我无法让它工作。

【问题讨论】:

  • 您的意思是要像这样格式化 x 和 y 轴上的刻度线的注释吗?
  • @tokamak - 目前实际上只对 y 轴感兴趣,但最好分别设置两个轴
  • 查看生成刻度线github.com/matplotlib/matplotlib/blob/… 的代码,似乎没有明显的方法可以自己更改它。我想一个非最佳方法是只创建该更改行 823 的修改版本。
  • @SimonGibbons,总有办法改变事情,你只需要知道去哪里看!在这种情况下,OP已经提到了FuncFormatter,这正是我们需要的工具

标签: python python-2.7 matplotlib


【解决方案1】:

您可以使用来自matplotlib.ticker 模块的FuncFormatter 来执行此操作。您需要一个关于刻度值是否大于或小于 1 的条件。因此,如果 log10(tick value)>0,则在标签字符串中添加 + 符号,如果不是,则它将获得其减号自动。

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

# sample data
x = y = np.logspace(-3,3)

# create a figure
fig,ax = plt.subplots(1)

# plot sample data
ax.loglog(x,y)

# this is the function the FuncFormatter will use
def mylogfmt(x,pos):
    logx = np.log10(x) # to get the exponent
    if logx < 0:
        # negative sign is added automatically  
        return u"$10^{{{:.0f}}}$".format(logx)
    else:
        # we need to explicitly add the positive sign
        return u"$10^{{+{:.0f}}}$".format(logx)

# Define the formatter
formatter = ticker.FuncFormatter(mylogfmt)

# Set the major_formatter on x and/or y axes here
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)

plt.show()

格式字符串的一些解释:

"$10^{{+{:.0f}}}$".format(logx)

双括号{{}} 被传递给LaTeX,表示它们中的所有内容都应该作为指数提高。我们需要双括号,因为 python 使用单括号来包含格式字符串,在本例中为{:.0f}。有关格式规范的更多说明,请参阅docs here,但 TL;DR 对于您的情况是我们正在格式化精度为 0 位小数的浮点数(即基本上将其打印为整数);在这种情况下,指数是一个浮点数,因为np.log10 返回一个浮点数。 (也可以将 np.log10 的输出转换为 int,然后将字符串格式化为 int - 只是您喜欢的偏好问题)。

【讨论】:

  • Ok thx,我要这么做了...你能解释一下{{:.0f}} 的格式吗?我猜是用过多的括号来转义,但:.0f 到底是做什么的?跨度>
【解决方案2】:

我希望这就是你的意思:

def fmt(y, pos):
    a, b = '{:.2e}'.format(y).split('e')
    b = int(b)
    if b >= 0:
      format_example = r'$10^{+{}}$'.format(b)
    else:
      format_example = r'$10^{{}}$'.format(b)
    return

然后使用FuncFormatter,例如对于颜色条:plt.colorbar(name_of_plot,ticks=list_with_tick_locations, format = ticker.FuncFormatter(fmt))。我认为您必须导入import matplotlib.ticker as ticker

问候

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多