【问题标题】:Display some text as bold using matplotlib [duplicate]使用matplotlib将一些文本显示为粗体[重复]
【发布时间】:2019-03-20 17:53:43
【问题描述】:

今天我正在处理一个图表,其中一部分有使用plt.text 的注释。在这个注释中,我想写一些类似的东西 "这个月的价格是:USD$3"

不加粗体,翻译成这样的代码:

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

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

在 SO 中有一个类似的问题,但对于标题,建议使用这样的符号:

"The price for this month is:' + r"$\bf{" + USD${df.price.iloc[-1]} + "}$"

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

你知道如果可以做到吗?如果可以,如何做到?

【问题讨论】:

    标签: python matplotlib text


    【解决方案1】:

    这是一种方法。您只需要将 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()
    

    更简洁:

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

    您也可以将格式设置为

    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]) + "}$")
    

    【讨论】:

    • 谢谢@Bazingaa!它运行良好。我还有一个问题:这种语法是否支持格式化?我还必须对浮点数和百分比执行此操作,所以我想知道是否必须通过 np.round() 手动格式化并乘以 100 并添加“%”?
    • @JuanC:检查我编辑的答案
    • 再次感谢!只是为了确保我理解正确,r"$ .... $' 表示法让您可以使用 html 编码来格式化图表的文本,对吗?
    • r"$...$" 启用 LaTeX 渲染
    • @JuanC:阅读this
    猜你喜欢
    • 2022-01-20
    • 2014-09-21
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多