使用 matplotlib 将一些文本显示为粗体

Jua*_*n C 4 python text matplotlib

今天我正在处理一个图表,其中一部分有使用的注释plt.text。在此注释中,我想写一些类似于“本月的价格是:USD$3 ”的内容

如果不加粗,则可以翻译成如下代码:

plt.text(0.5,0.9, f"The price for this month is: USD${df.price.iloc[-1]}")
Run Code Online (Sandbox Code Playgroud)

所以,我想做的就是USD${df.price.iloc[-1]}在打印到图表时将其变为粗体。

SO 中有一个类似的问题,但对于标题,建议使用如下所示的符号:

"The price for this month is:' + r"$\bf{" + USD${df.price.iloc[-1]} + "}$"
Run Code Online (Sandbox Code Playgroud)

但该语法似乎无效,所以我不确定是否可能有一个包含粗体和非粗体部分的文本。

您知道是否可以做到,如果可以,如何做到?

She*_*ore 9

这是一种方法。您只需将 DataFrame 值转换为字符串


完整答案

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'price': [2, 4, 8, 3]}, index=['A', 'B', 'C', 'D'])

fig = plt.figure()

plt.text(0.1,0.9, r"The price for this month is: "+ r"$\bf{USD\$" + str(df.price.iloc[-1])  + "}$")
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

甚至简洁:

plt.text(0.1,0.9, r"The price for this month is: $\bf{USD\$ %s}$" % str(df.price.iloc[-1]) )
Run Code Online (Sandbox Code Playgroud)

您还可以使用格式设置为

fig = plt.figure()

plt.text(0.1,0.9, r"The price for this month is: " + r"$\bf{USD\$" + '{:.2f}'.format(df.price.iloc[-1]) + "}$")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述