解决方案pyspark 绘图报错:_tkinter.TclError: no display name and no $DISPLAY environment variable

Posted Sinsa_SI

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决方案pyspark 绘图报错:_tkinter.TclError: no display name and no $DISPLAY environment variable相关的知识,希望对你有一定的参考价值。

问题描述

matplotlib画图失败(pyspark、pyspark3),报错如下:

no display name and no $DISPLAY environment variable
Traceback (most recent call last):
  File "<stdin>", line 21, in plot_with_labels
  File "/usr/install/anaconda3-spark/lib/python3.6/site-packages/matplotlib/pyplot.py", line 539, in figure
    **kwargs)
  File "/usr/install/anaconda3-spark/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 171, in new_figure_manager
    return cls.new_figure_manager_given_figure(num, fig)
  File "/usr/install/anaconda3-spark/lib/python3.6/site-packages/matplotlib/backends/backend_tkagg.py", line 1049, in new_figure_manager_given_figure
    window = Tk.Tk(className="matplotlib")
  File "/usr/install/anaconda3-spark/lib/python3.6/tkinter/__init__.py", line 2017, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

解决方案

利用matplotlib画图需要设置 plt.switch_backend('agg')

显示图像用魔法命令 %matplot plt 需要单独 cell 执行

示例代码

import matplotlib.pyplot as plt
plt.switch_backend("agg")
import numpy as np
x = np.arange(9)
y = np.sin(x)
z = np.cos(x)
plt.plot(x,y,marker="*",linewidth=3,linestyle="--",color="orange")
plt.plot(x,z)
plt.title("matplotlib")
plt.xlabel("height")
plt.ylabel("width")
plt.legend(["Y","Z"],loc="upper right")
plt.grid(True)

参考链接:https://stackoverflow.com/questions/3453188/matplotlib-display-plot-on-a-remote-machine

以上是关于解决方案pyspark 绘图报错:_tkinter.TclError: no display name and no $DISPLAY environment variable的主要内容,如果未能解决你的问题,请参考以下文章

Debug系列ImportError: No module named ‘_tkinter‘

matplotlib报错_tkinter.TclError: no display name and no $DISPLAY environment variable

完美解决ModuleNotFoundError: No module named ‘_tkinter‘错误

python3 tkinter报错:_tkinter.TclError: cannot use geometry manager pack inside . which already has sla

Linux终端没有GUI,如何使用matplotlib绘图

Python中pyspark_map数据计算方法