在matplotlib中以粗体显示字符串变量的更简单方法 [英] Easier way to print in bold a string variable in matplotlib

查看:104
本文介绍了在matplotlib中以粗体显示字符串变量的更简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我遇到了一个非常的问题:我想使用 plt.text() 在函数内以粗体打印一个字符串变量.当我将 mathtext 与常规语法混合时,我觉得我将Python的图形处理能力推到了极限.

所以,函数的重要部分是这样的:

  def graph_text(var):string0 = f'字符串为:'+ r"$ \ bf {" + var +} $"plt.text(string0)

事情是 var 是一些字符串,可以包含一到三个单词.默认情况下,mathtext 中的字符串是串联的,因此,对于 var='the dog',这将打印 'String is thedog'.

然后我尝试使用 split()'\/\'.join(),如下所示:

string0=f'String 为:'+r"$\bf{"+('\/\'.join(var.split()))+"}$"

('\/\'是 mathtext 中的空格,但是由于这里不属于 mathtext 语法,因此将其解释为scape字符并带来一个 SyntaxError .因此,我唯一能找到的解决方案是手动执行以下操作:

 如果 len(var)==1:string0=f'字符串是:'+r"$\bf{"+var.split()[0]+"}$"elif len(var)== 2:string0=f'字符串为:'+r"$\bf{"+var.split()[0]+r" $\bf{"+var.split()[1]+"}$"别的:(插入相同的代码,但输入三个单词)

那么,您知道是否有一种无需考虑所有可能情况就可以做到的方法吗?谢谢

解决方案

在编写 LaTeX 文档时,我使用 \; 在数学模式下放置一个空格.它似乎也适用于此.

plt.text(0,0,r'String is $\bf{{{}}}$'.format(var.replace(' ', r'\;')))

我建议使用 str.format() 而不是连接您的字符串,因为这样可以让您在下次查看时更清晰.

Today I'm having a very specific issue: I want to print a string variable inside a function using plt.text() in bold. I feel I'm pushing Python's graphing capabilities to the limit when mixing mathtext with the usual syntax.

So, the important part of the function looks like this:

def graph_text(var):
    string0=f'String is:'+r"$\bf{"+var+"}$"
    plt.text(string0)

The thing is var are some strings that can have between one and three words. By default in mathtext strings are concatenated, so, for var='the dog' this would print 'String is thedog'.

I then tried using split() and '\/\'.join(), like this:

string0=f'String is:'+r"$\bf{"+('\/\'.join(var.split()))+"}$"

( '\/\' is a space in mathtext, but because here we're outside of mathtext syntax, this is interpreted as a scape character and brings a SyntaxError. So, the only solution I could find is to manually do it like this:

 if len(var)==1:
    string0=f'String is:'+r"$\bf{"+var.split()[0]+"}$"
elif len(var)==2:
    string0=f'String is:'+r"$\bf{"+var.split()[0]+r" $\bf{"+var.split()[1]+"}$"
else:
    (insert same code but for three words)

So, do you know if there's a way to do it without having to account for every possible case? Thanks

解决方案

When writing LaTeX documents I use \; to put a space when in math mode. It also appears to work here.

plt.text(0,0,r'String is $\bf{{{}}}$'.format(var.replace(' ', r'\;')))

I suggest using str.format() instead of concatenating your strings because it makes your intent clearer the next time you look at it.

这篇关于在matplotlib中以粗体显示字符串变量的更简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆