格式化负数货币

huangapple go评论67阅读模式
英文:

Formatting negative currency

问题

I want to plot negative currency amounts as labels. Here is some code that I found:

fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
axes.yaxis.set_major_formatter(tick)

This will show negative $45 as $-45 on the Y-axis. What is the correct format to display -$45 instead?

Note: This question was closed because the same question was asked before. However, if you check the answer to that earlier question, it does not work for negative currencies, leading to the exact problem discussed in my question below, which has an accepted answer. Indeed, the solution in the older question was to use fmt = '${x:,.0f}'.

英文:

I want to plot negative currency amounts as labels. Here is some code that I found:

fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
axes.yaxis.set_major_formatter(tick)

This will show negative $45 as $-45 on the Y-axis. What is the correct format to display -$45 instead?

Note: This question was closed because the same question was asked before. However, if you check the answer to that earlier question, it does not work for negative currencies, leading to the exact problem discussed in my question below, which has an accepted answer. Indeed, the solution in the older question was to use fmt = '${x:,.0f}'.

答案1

得分: 3

你可以定义一个自定义的刻度函数,根据刻度值是正数还是负数来格式化刻度标签,查看这个示例:

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

x = np.arange(5)
y = np.array([-100, -50, 0, 50, 100])

# 自定义刻度函数
def currency_ticks(x, pos):
    if x >= 0:
        return '${:,.0f}'.format(x)
    else:
        return '-${:,.0f}'.format(abs(x))

fig, ax = plt.subplots()

ax.plot(x, y)

# 使用自定义函数格式化y轴刻度标签
tick = mtick.FuncFormatter(currency_ticks)
ax.yaxis.set_major_formatter(tick)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Title')

plt.show()

这段代码演示了如何使用自定义刻度函数来格式化图表的刻度标签,根据刻度值的正负显示不同的货币格式。

英文:

You can define a custom tick function that formats the tick labels based on whether they are positive or negative, check this example:

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

x = np.arange(5)
y = np.array([-100, -50, 0, 50, 100])

# custom tick function
def currency_ticks(x, pos):
    if x >= 0:
        return '${:,.0f}'.format(x)
    else:
        return '-${:,.0f}'.format(abs(x))

fig, ax = plt.subplots()

ax.plot(x, y)

# format the y-axis tick labels using custom func
tick = mtick.FuncFormatter(currency_ticks)
ax.yaxis.set_major_formatter(tick)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Title')

plt.show()

huangapple
  • 本文由 发表于 2023年5月13日 12:41:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定