简体   繁体   中英

Formatting of title in Matplotlib

I have the following python code:

def plot_only_rel():
    filenames = find_csv_filenames(path)
    for name in filenames:
        sep_names = name.split('_')
        Name = 'Name='+sep_names[0]
        Test = 'Test='+sep_names[2]
        Date = 'Date='+str(sep_names[5])+' '+str(sep_names[4])+' '+str(sep_names[3])
    plt.figure()
    plt.plot(atb_mat_2)
    plt.title((Name, Test, Date))

However when I print the title on my figure it comes up in the format

(u'Name=X', u'Test=Ground', 'Date = 8 3 2012')

I have the questions: Why do I get the 'u'? Howdo I get rid of it along with the brackets and quotation marks? This also happens when I use suptitle.

Thanks for any help.

plt.title receives a string as it's argument, and you passed in a tuple (Name, Test, Date) . Since it expects a string it tried to transform it to string using the tuple's __str__ method which gave you got output you got. You probably want to do something like:

plat.title('{0} {1}, {2}'.format(Name, Test, Date))

How about:

plt.title(', '.join(Name,Test,Date))

Since you are supplying the title as an array, it shows the representation of the array (Tuple actually). The u tells you that it is an unicode string.

You could also use format to specify the format even better:

plt.title('{0}, {1}, {2}'.format(Name, Test, Date))

在 Python > 3.6 中,您甚至可以使用 f-string 来简化格式化:

plt.title(f'{Name}, {Test}, {Date}')

I'd like to add to @Gustave Coste's answer: You can also use lists directly in f-strings

s="Santa_Claus_24_12_2021".split("_")
print(f'Name={s[0]}, Test={s[1]}, Date={s[2]} {s[3]} {s[4]}')

result: Name=Santa, Test=Claus, Date=24 12 2021 . Or for your case:

plt.title(f'Name={sep_names[0]}, Test={sep_names[2]}, Date={sep_names[5]} {sep_names[4]} {sep_names[3]}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM