matplotlib bug1:TypeError_ ‘tuple‘ object is not callable; matplotlib figsize.

Problem Description

When I was using matplotlib to draw a picture today, a very magical thing happened, plt.figure()it doesn't work!

The specific code is as follows:

# 调用库
import pandas as pd
import matplotlib.pyplot as plt
# 生成数据框,x为0~50,y为x的平方
df = pd.DataFrame([i/2 for i in range(100)],columns=['x'])
df['y2'] = df.x.apply(lambda x:x*x)
# 绘图
fig = plt.figure(figsize=(10,10))   # 指定画布大小
plt.plot(df.x,df.y2,label='y=x^2')  
# 加注释
plt.annotate(r'y=x^2'            # 标签
             ,xycoords='data'
             ,xy=(40,40*40)      # 指向点
             ,textcoords='offset points'
             ,xytext=(-50,40)    # 注释位置
             ,fontsize=15        # 字号
             ,c='b'              # 颜色
             ,arrowprops=dict(arrowstyle='->'           # 指向点使用的线
                              ,connectionstyle='angle3' # 线类型
                             ))
plt.show()

After running, an error is reported, which points to line 6 fig = plt.figure(figsize=(10,10)):

TypeError: ‘tuple’ object is not callable; matplotlib figsize.

This error report is very nonsensical at first glance. How did it become a tuple object that cannot be called figsize()?
And there is no problem when copying the code to other places to run, but there is a problem when running at this time.

Solution

In a later coincidence, I suddenly realized the source of the error, that is, at the beginning, I wrote the wrong code, as follows (interested friends can reproduce it~)

 plt.figure = (1010)

plt.figureIt was originally a function, but it was assigned a tuple by me, so the later code plt.figure(figsize=(10,10))became that (10,10)(figsize=(10,10))the tuple was regarded as a function call figsize, so an error was reported.

This error may only appear in environments where variables are temporarily stored, such as jupyter notebooks and test environments, because such environments store the assignments that I wrote wrong earlier. If the code is run directly through a compiler (such as vscode, pycharm, etc.), the variable will become invalid after the running, and there will be no errors caused by such wrong assignments.

The solution is very simple, restart the kernel, and then re-run the code , you can draw normally.
insert image description here

Guess you like

Origin blog.csdn.net/qq_45476428/article/details/127771667