英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论