错误复现
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(1000)
y = np.sin(2*math.pi*x/1000)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.title("sine") # 报错:TypeError: 'Text' object is not callable
报错
TypeError: 'Text' object is not callable
解决办法
仔细翻阅matplotlib的官方API手册发现ax根本没有title这个接口,正确的接口是set_tile。所以,ax.title → ax.set_tile,就行了。
plt.title和ax.set_title
matplotlib的官方API手册还是很有用的,仔细看plt.title和ax.set_title实现的是同样的功能。很想给作者团队提意见:为什么不统一接口?
不过使用者也应该认真阅读手册啊。
看不懂手册怎么办?没关系,关注我就行啦,带你看手册。
添加title的两种方式
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(1000)
y = np.sin(2*math.pi*x/1000)
# 使用plt.title
plt.plot(x, y)
plt.title("sine")
# 使用ax.set_tile
fig, ax = plt.subplots()
ax.plot(x, y)
# ax.title("sine") # 报错:TypeError: 'Text' object is not callable
ax.set_title("sine") # 正确的打开方式
see also
- matplotlib官方API手册:ax.set_title
- matplotlib官方API手册:plt.title