【错误及解决】Linux终端无GUI调用matplotlib绘图问题解决

一、问题描述

采用Xshell连接linux服务器,然后调用matplotlib作图,由于没有GUI所以想把图像保存下来,然后下载到本地查看。网上给了有效方案如下:

import matplotlib
matplotlib.use("Agg")  #这一句一定要放在下面这句的前面
 
import matplotlib.pyplot as plt

但是 我按照这个方法写成如下,会报错显示x11转发请求,总之就是不能正常保存图片

import os
import numpy as np
from Config import Config
import net
from keras.utils import to_categorical
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
import mit_utils as utils
import time
from keras.models import load_model


os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2'
os.environ["CUDA_VISIBLE_DEVICES"] = '3'
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session

import matplotlib
matplotlib.use("Agg")
 
import matplotlib.pyplot as plt



###中间省略N行代码
#*******************************
history = model.fit(x=TrainXt, y=TrainYt, batch_size=modelconfig.batch_size, epochs=3,
              verbose=1, validation_data=(ValXt, ValYt), callbacks=callback_lists)
plt.plot(history.history['categorical_accuracy'], marker='.')
plt.plot(history.history['val_categorical_accuracy'], marker='.')
plt.title('model accuracy')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.grid()
plt.legend(['categorical_accuracy', 'val_categorical_accuracy'], loc='lower right')
plt.savefig(os.path.join(result_dir, 'model_accuracy.png'))
plt.close()

plt.plot(history.history['loss'], marker='.')
plt.plot(history.history['val_loss'], marker='.')
plt.title('model loss')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.grid()
plt.legend(['loss', 'val_loss'], loc='upper right')
plt.savefig(os.path.join(result_dir, 'model_loss.png'))
plt.close()

然后就会出现如下弹框。。。。
在这里插入图片描述

二、解决方案

我试了很多次,最终发现把matplotlib的调用放在最前面就可以了~~~~
像下面这样,不过我不知道什么原理,如果有大佬晓得,请在评论区指点一下呀!

import matplotlib
matplotlib.use("Agg")
 
import matplotlib.pyplot as plt

import os
import numpy as np
from Config import Config
import net
from keras.utils import to_categorical
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
import mit_utils as utils
import time
from keras.models import load_model


os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2'
os.environ["CUDA_VISIBLE_DEVICES"] = '3'
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,我可以帮你写一个Python GUI程序,使用Matplotlib库来画出输入函数及其一阶导数的图形。下面是一个简单的实现: ```python import tkinter as tk from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import numpy as np class PlotWindow: def __init__(self, master): self.master = master master.title("Plot Window") # 创建输入函数文本框和按钮 self.input_label = tk.Label(master, text="输入函数:") self.input_label.grid(row=0, column=0) self.input_entry = tk.Entry(master, width=50) self.input_entry.grid(row=0, column=1) self.plot_button = tk.Button(master, text="绘制图形", command=self.plot) self.plot_button.grid(row=0, column=2) # 创建绘图区域 self.fig = Figure(figsize=(5, 4), dpi=100) self.ax = self.fig.add_subplot(111) self.canvas = FigureCanvasTkAgg(self.fig, master=master) self.canvas.get_tk_widget().grid(row=1, column=0, columnspan=3) def plot(self): # 获取输入函数并计算一阶导数 func = self.input_entry.get() f = lambda x: eval(func) x = np.linspace(-5, 5, 1000) y = f(x) dy = np.gradient(y, x) # 清空绘图区域并绘制函数图形和一阶导数图形 self.ax.clear() self.ax.plot(x, y, label="函数图像") self.ax.plot(x, dy, label="一阶导数图像") self.ax.legend() # 更新绘图区域 self.canvas.draw() root = tk.Tk() app = PlotWindow(root) root.mainloop() ``` 这个程序使用了Tkinter库来创建GUI界面,并使用Matplotlib库来绘制图形。程序中包含一个文本框和一个按钮,用于输入函数及绘制图形。在绘图函数中,我们使用`numpy`库来生成一组x坐标点,然后通过输入函数计算相应的y坐标点和一阶导数,最后调用Matplotlib的`plot`函数来绘制函数图形和一阶导数图形。 请注意,这个程序只是一个简单的示例,对于复杂的函数和绘图需求可能需要进行更多的优化和改进。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值