首页 > 解决方案 > 无法在 matplotlib 文本中打印 $

问题描述

我正在尝试在 python3 中使用 matplotlib 生成的图形上放置一个带有两个美元符号 ($) 的文本字符串。我正在使用默认 mac 后端的 mac 上运行。我也尝试过 TKAgg,结果相同。

这是我的示例代码:

import matplotlib.pyplot as plt

fig = plt.figure()

text = "first $" + str(10.95) + ", second $" + str(20.99)
print (text)

plt_text = plt.text(0.5,0.5,text,va='center',ha='center')

plt.show()

期望的输出是“第一个 $10.95,第二个 $20.99”。相反,我得到: “first 10.95, second20.99 如果图像不可用,我可能会注意到单词 second 已更改为斜体。 print(text) 在控制台中正常工作。

如果字符串只包含一个 $,则显示正确。如果我使用双美元符号 ($$),我会得到一个错误。单美元符号和双美元符号的不同组合未正确显示。

标签: pythonmatplotlibtext

解决方案


Matploitlib 假设美元符号 ($) 是乳胶符号,以指示乳胶的开始或结束。您需要对其进行转义才能将其打印为任何其他字符。更多的

text = "first \$" + str(10.95) + ", second \$" + str(20.99)

推荐阅读