Easier way to print in bold a string variable in matplotlib

牧云@^-^@ 提交于 2021-02-11 13:40:58

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/55287015/easier-way-to-print-in-bold-a-string-variable-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!