【问题标题】:Plot matplotlib by running python file通过运行 python 文件绘制 matplotlib
【发布时间】:2021-09-12 22:02:58
【问题描述】:

所以有this thread在谈论为什么matplotlib在执行时不显示

python myfile.py

最受欢迎的答案是关于resetting matplotlibrc 文件。需要在此文件中重置哪些内容?

另外,有些人建议在导入中包含matplotlib.use('TkAgg')。下面是我的python文件:

#myfile.py

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np


def dyn_draw():
    x = np.linspace(0, 6 * np.pi, 100)
    y = np.sin(x)

    plt.ion()

    fig = plt.figure()
    ax = fig.add_subplot(111)
    line1, = ax.plot(x, y, 'r-')  # Returns a tuple of line objects, thus the comma

    for phase in np.linspace(0, 10 * np.pi, 500):
        line1.set_ydata(np.sin(x + phase))
        fig.canvas.draw()
        fig.canvas.flush_events()

if __name__ == "__main__":
    dyn_draw()

使用python myfile.py 运行,我收到以下错误:

ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running

另一个线程here 讨论了这个错误。但是解决方案仍然不起作用(即重新启动内核)。

如何使用python 命令绘制这个特定的python 代码?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您正在尝试在非交互式环境中以交互方式运行 matplotlib。代码可以编译,但在运行时出错,因为您运行的是脚本。

    你试过在Google Colab 中运行它吗?该资源为交互式可视化提供免费(在一定程度上)GPU 使用和块编码。

    祝你好运:)

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      相关资源
      最近更新 更多