简体   繁体   中英

Is there a way to make axis labels bold and italic in matplotlib

I am plotting several (hundred) figures in a loop in python. The axis labels are based on a combination of strings and predetermined variable names. I and need to include both italic and bold font but am not entirely sure how to achieve this. I've tried searching for other stackoverflow posts and on various google searches, but haven't turned up anything.

myvariable ="This changes in each loop" # needs to be bold verb = "This changes in each loop too" # needs to be italic

# I would like myvariable to be in bold text 
# I would like "Less" and verb and "More" and verb to be in italic text

plt.ylabel(myvariable + "\n" + "Less" + verb + "       " + "More" + verb)

Is there a way to format a variable name in italics (perhaps similar to r"$\\it{some text}$" where instead of a predetermined string, the italicized text is a variable that changes in each loop for each new figure? Or even something like str.upper(myvairable) where instead of uppercase it is bold or italic font? Although hardcoding the variables could technically work, is not really an option for me since there are hundreds of graphs to plot.

Would really appreciate some help!

Thanks in advance

I found an answer! from here : Easier way to print in bold a string variable in matplotlib

Probably not super elegant, but, instead of verb I used r"$\\it{{{}}}$".format(verb.replace(' ', r'\\;')) . This adds the variable name in rather than just the raw text and formats it exactly as I would like. Same can be used for bold font too. Full code for my solution was:

plt.ylabel(str.upper(my_variable) + " (years)" + "\n" + r"$\longleftarrow$" + r"$\it{Less}$" + " " +  r"$\it{{{}}}$".format(verb.replace(' ', r'\;')) +  
               "                       " + r"$\it{More}$" + " " + r"$\it{{{}}}$".format(verb.replace(' ', r'\;')) + r"$\longrightarrow$", fontname="Arial Bold",fontsize=14,
    fontweight="bold",labelpad=5, color="black")

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