【解决方案】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 "", 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)

【解决方案】pyspark 绘图报错:_tkinter.TclError: no display name and no $DISPLAY environment variable_第1张图片

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

你可能感兴趣的:(Spark,Python,问题&解决方案)