使用plt.title()报错'str' object is not callable,赋值后标题不显示
问题:Matplotlib绘图时设置坐标轴标签和标题报错或不显示
原代码
#import the necessary modules import math import matplotlib.pyplot as plt #initialize the two empty lists and set it as y and y2 y = [] y2 = [] #iterate through 1-10 for the value of x for x in range(1, 11): #store the equation into two lists y += [x ** 2 + 3 - math.log(x)] y2 += [x ** 2 + 3 + math.log(x)] #plot y and add the lable plt.plot(range(1, 11), y, label = 'subtracting log(x)') #plot y2 and add the lable, also, turn the color into red plt.plot(range(1, 11), y2 ,color = 'red', label = 'adding log(x)') #set the lable of x and y axis plt.xlabel = 'x-axis' plt.ylabel = 'y-axis' plt.title("Plot of y = x^2 + 3 - log(x) and y = x^2 + 3 + log(x)") plt.legend() plt.show()
报错信息
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /var/folders/8q/q_5rzwtd5qx5mpvf4r9v10_40000gn/T/ipykernel_59793/986723238.py in <module> 23 plt.ylabel = 'y-axis' 24 ---> 25 plt.title("Plot of y = x^2 + 3 - log(x) and y = x^2 + 3 + log(x)") 26 plt.legend() 27 plt.show() TypeError: 'str' object is not callable
将plt.title("...")改为plt.title = "..."后,代码可运行但图表标题不显示,且反复触发上述报错。
错误原因
你把Matplotlib中设置标签、标题的函数当成普通变量赋值了:
plt.xlabel、plt.ylabel、plt.title都是Matplotlib提供的函数,必须通过函数名(参数)的方式调用,不能直接赋值字符串。- 执行
plt.xlabel = 'x-axis'时,已经把原本的plt.xlabel函数覆盖成了字符串对象,污染了当前运行环境中的Matplotlib对象,导致后续调用plt.title时触发错误。
修正后的代码
把错误的赋值语句改成函数调用即可:
#import the necessary modules import math import matplotlib.pyplot as plt #initialize the two empty lists and set it as y and y2 y = [] y2 = [] #iterate through 1-10 for the value of x for x in range(1, 11): #store the equation into two lists y += [x ** 2 + 3 - math.log(x)] y2 += [x ** 2 + 3 + math.log(x)] #plot y and add the lable plt.plot(range(1, 11), y, label = 'subtracting log(x)') #plot y2 and add the lable, also, turn the color into red plt.plot(range(1, 11), y2 ,color = 'red', label = 'adding log(x)') #set the lable of x and y axis - 改为函数调用 plt.xlabel('x-axis') plt.ylabel('y-axis') #标题用函数调用 plt.title("Plot of y = x^2 + 3 - log(x) and y = x^2 + 3 + log(x)") plt.legend() plt.show()
额外提示
如果修改后仍报错,建议重启Python内核/运行环境——之前的错误赋值已经修改了环境中的Matplotlib对象,重启后可恢复默认状态。
内容的提问来源于stack exchange,提问作者Nixon Ng
相关产品推荐
相关产品推荐

