【问题标题】:Recurring problem with plotting graphs in WSL Ubuntu在 WSL Ubuntu 中绘制图形的反复出现的问题
【发布时间】:2020-07-10 01:45:55
【问题描述】:

我正在编写一个应该绘制一个简单函数的代码,它暂时可以工作,但是当我重新启动计算机时,我一直遇到这个问题循环:

  1. 我第一次尝试运行代码时,它没有发出任何错误,但也没有创建任何图表。

--> 为了解决这个问题,我安装了 Xming 并在 bash 中编写了 export DISPLAY=localhost:0.0 命令,正如 AwokeKnowingShow matplotlib plots in Ubuntu (Windows subsystem for Linux) 中所建议的那样。

  1. 当我运行代码时,通过上述调整,我得到以下错误:
_tkinter.TclError: no display name and no $DISPLAY environment variable.

--> 为了解决这个问题,我添加了这行代码:

matplotlib.use('Agg')

正如 Serenity_tkinter.TclError: no display name and no $DISPLAY environment variable 中提出的

  1. 执行此操作并运行代码后,最初的图形会正确。但如果我改天再试一次,它不会。代码运行正常,但没有显示图表。

--> 为了让它工作,我删除了这行代码:

matplotlib.use('Agg')

通过这样做,代码再次绘制图表。

然后,当我重新启动计算机时,一系列问题又重新开始了。

有谁知道我做错了什么?我对使用 Python 很陌生,所以我很可能遗漏了一些明显的东西。

以下是我的代码的相关部分:

#Imports
import matplotlib
import matplotlib.pyplot as ply
from dolfin import *
import numpy as np
from mshr import *
import math
from math import exp

plt.plot(tiemporeal,fcmM1)
plt.xlabel('Tiempo')
plt.ylabel('Resistencia')
plt.show()

非常感谢,对于可能的格式错误,我们深表歉意。

PS。我在 Ubuntu 上使用 Python3。

【问题讨论】:

    标签: python ubuntu matplotlib plot xming


    【解决方案1】:

    对于旧版 WSL,添加就足够了

    export DISPLAY=127.0.0.1:0
    

    到您的~/.bashrc 文件 - 默认后端应该可以正常工作。对于 WSL 2,它更复杂,您需要从 /etc/resolv.conf 获取服务器的名称,然后从 ifconfig 获取掩码。例如在我的系统上:

    wmiller@lcl:~$ cat /etc/resolv.conf
    # This file was automatically generated by WSL. To stop automatic generation of this file,
    # add the following entry to /etc/wsl.conf:
    # [network]
    # generateResolvConf = false
    nameserver 172.28.176.1
    

    wmiller@lcl:~$ ifconfig | grep 'inet '
            inet 172.28.176.7  netmask 255.255.240.0  broadcast 172.28.191.255 
            inet 127.0.0.1  netmask 255.0.0.0
    

    所以我的DISPLAY 必须是172.28.176.7:240.0。自动提取有点复杂,但是将以下命令添加到 ~/.bashrc 对我有用:

    export DISPLAY=$((ifconfig | grep -f <(cat /etc/resolv.conf | grep nameserver |
                      awk -F'[. ]' '{print $2"."$3}') | awk '{for(i=1; i <=NF; i++) 
                      {if($i == "inet") print $(i+1)}}' ; ifconfig | 
                      grep -f <(cat /etc/resolv.conf | grep nameserver | 
                      awk -F'[. ]' '{print $2"."$3}') | 
                      awk '{for(i=1; i <=NF; i++) {if($i == "netmask") print $(i+1)}}' | 
                      awk -F'.' '{print $3"."$4}') 
                     | tr "\n" " " | awk '{print $1":"$2}')
    

    在任何一种情况下,您可能还需要在 xserver 客户端中禁用访问控制 - 我不确定 Xming 但 vcxsrv 只需要命令行参数 -ac 或在启动期间检查禁用访问控制。您还需要确保 Windows 防火墙允许连接。您可能会发现this thread 很有用。

    还要注意'Agg' 是一个非gui 后端,使用它不会显示数字。我发现我的设置 'TkAgg' 效果最好。

    【讨论】:

    • 将显示环境更改为“TkAgg”就可以了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多