简体   繁体   中英

print mathematical expression in python

I am having problem writing the title for my plot. There is a for loop that generate N plots and each plot should have a specific title. For example in one of the loops, title is 100^{2.4}_{5.6}. I have the following code but it only put the first digit of upper/lower value.

a=[100,200,300]
b=[2.4,3.5,6.7]
c=[5.6,1.3,4.2]
for i in plots:

    plt.title(r"${}^{}_{}$".format(a[i],b[i],c[i]))

Which in this example a[1]=100, b[1]=2.4, c[1]=5.6. What this code outputs is 100^{2}.4_{5}.6!!!

What you want can be done using the f strings formatting as:

a = [100, 2.4, 5.6]
plt.title(f"${a[0]}^{ {a[1]} }_{ {a[2]} }$")
# Text(0.5, 1.0, '$100^{2.4}_{5.6}$')

In this example I have taken a hypotetical list a but obviously it works for any number you use.

The {} from .format interferes with the {} from LaTeX.

Using the old formatting, you get the expected result:

plt.title(r"$%d^{%.1f}_{%.1f}$" %(a[i], b[i], c[i]))

Basically things like "$x_12$" create something that looks like "$x_1 2$" so you need to use brackets for any sub/superscript that uses more than one character.

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