I want to use the variable DelG_Zero in the legend. I tried the following (by referring to previous stackoverflow posts) and did not work. How do I resolve this?
Error message:
File "<ipython-input-187-b5fccd6494bb>", line 13, in <module>
plt.legend([r'$\Delta G_0 = {}$',r'$\Delta G_0={}$',r'$\Delta G_0={}$'].format([DelG_Zero[0],DelG_Zero[1],DelG_Zero[2]]),fontsize=12)
AttributeError: 'list' object has no attribute 'format'
Code:
import numpy as np
import matplotlib.pyplot as plt
DelG_Zero =[2.8,5,7]
fig = plt.figure()
lines = plt.plot(range(10), np.random.randn(10), range(10), np.random.randn(10), range(10), np.random.randn(10))
plt.legend([r'$\Delta G_0 = {}$',r'$\Delta G_0={}$',r'$\Delta G_0={}$'].format([DelG_Zero[0],DelG_Zero[1],DelG_Zero[2]]),fontsize=12)
plt.show()
You are calling .format
on the list of strings, not each string itself. A list
doesn't have a .format
method, so an AttributeError
is raised.
To solve this, you should directly format the strings:
plt.legend([r"$\Delta G_0 = {}$".format(x) for x in DelG_Zero], fontsize=12)
If you're using Python 3.6 or later, you can use f-strings for slightly cleaner syntax:
plt.legend([rf"$\Delta G_0 = {x}$" for x in DelG_Zero], fontsize=12)
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.