Ashleigh Clayton
Ashleigh Clayton

Reputation: 1445

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.

Upvotes: 1

Views: 14470

Answers (4)

DomTomCat
DomTomCat

Reputation: 8569

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]}')

Upvotes: 0

Gustave Coste
Gustave Coste

Reputation: 707

In Python > 3.6 you may even use f-string for easier formatting:

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

Upvotes: 0

Viktor Kerkez
Viktor Kerkez

Reputation: 46566

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))

Upvotes: 3

Qiau
Qiau

Reputation: 6165

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))

Upvotes: 0

Related Questions