Pycharm使用matplotlib绘图时报错
问题描述
TypeError: vars() argument must have __dict__ attribute
源程序:
# -*- encoding: utf-8 -*-
'''
@File : MaLearnTest01_1.py
@Time : 2023/03/03 09:39:05
@Author : seveN1foR
@Version : 1.0
@Contact : sevencdxxiv@qq.com
'''
# here put the import lib
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def draw(FillStyle):
x_coords = np.linspace(-100, 100, 500)
y_coords = np.linspace(-100, 100, 500)
points = []
for y in y_coords:
for x in x_coords:
if ((x * 0.03) ** 2 + (y * 0.03) ** 2 - 1) ** 3 - (x * 0.03) ** 2 * (y * 0.03) ** 3 <= 0: # 引用公式
points.append({"x": x, "y": y})
heart_x = list(map(lambda point: point["x"], points))
heart_y = list(map(lambda point: point["y"], points))
if FillStyle == 1:
plt.scatter(heart_x, heart_y, s=10, alpha=0.5)
else:
plt.scatter(heart_x, heart_y, s=10, alpha=0.5, c=range(len(heart_x)), cmap='autumn')
plt.show()
print(mpl.get_backend())
# 主过程
fStyle = 2
draw(fStyle)
运行结果:
原因分析:
在 PyCharm(至少在科学项目中)使用交互式控制台运行所有文件,其中使用了后端 module://backend_interagg。 这个后端会导致与您相同的错误。所以。 在你的文件头部添加 mpl.use(‘TkAgg’) ,或者检查你可以使用哪个后端并在此函数中传递这些名称。
解决方案:
在你的文件头部添加 mpl.use(‘TkAgg’) ,或者检查你可以使用哪个后端并在此函数中传递这些名称。
但是在某些情况下,TkAgg 可能不可用。 第一次检查时,您使用的是哪个后端。 为此,运行这个简单的代码:
import matplotlib as mpl
print(mpl.get_backend())
但你必须在 PyCharm 之外的默认终端中手动运行。 (例如创建简单的 test.py 文件,粘贴代码,然后运行 python test.py)
头部添加use后的代码:
# -*- encoding: utf-8 -*-
'''
@File : MaLearnTest01_1.py
@Time : 2023/03/03 09:39:05
@Author : seveN1foR
@Version : 1.0
@Contact : sevencdxxiv@qq.com
'''
# here put the import lib
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use('TkAgg') # !IMPORTANT 更改在这里!!!!!!!!!
"""
Why? Because PyCharm (at least in scientific projects) runs all files with an interactive console,
where backend module://backend_interagg is used.
And this backend causes the same error as you have.
So. add mpl.use('TkAgg') in head of your file,
or checkout which backend you can use and past those name in this function.
"""
def draw(FillStyle):
x_coords = np.linspace(-100, 100, 500)
y_coords = np.linspace(-100, 100, 500)
points = []
for y in y_coords:
for x in x_coords:
if ((x * 0.03) ** 2 + (y * 0.03) ** 2 - 1) ** 3 - (x * 0.03) ** 2 * (y * 0.03) ** 3 <= 0: # 引用公式
points.append({"x": x, "y": y})
heart_x = list(map(lambda point: point["x"], points))
heart_y = list(map(lambda point: point["y"], points))
if FillStyle == 1:
plt.scatter(heart_x, heart_y, s=10, alpha=0.5)
else:
plt.scatter(heart_x, heart_y, s=10, alpha=0.5, c=range(len(heart_x)), cmap='autumn')
plt.show()
print(mpl.get_backend())
# 主过程
fStyle = 2
draw(fStyle)
运行结果:
文章来源:https://www.toymoban.com/news/detail-515097.html
参考文章源地址:
https://stackoverflow.com/questions/75453995/pandas-plot-vars-argument-must-have-dict-attribute文章来源地址https://www.toymoban.com/news/detail-515097.html
到了这里,关于Pycharm使用matplotlib报错:TypeError: vars() argument must have __dict__ attribute 解决方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!