You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Julia脚本运行正常但绘图无法显示的问题排查与解决

问题描述

我有一个名为mycode.jl的文件,代码取自MultivariateStats官方文档的PCA示例,内容如下:

using MultivariateStats, RDatasets, Plots

# load iris dataset
println("loading iris dataset:")
iris = dataset("datasets", "iris")
println(iris)
println("loaded; splitting dataset: ")

# split half to training set
Xtr = Matrix(iris[1:2:end,1:4])'
Xtr_labels = Vector(iris[1:2:end,5])

# split other half to testing set
Xte = Matrix(iris[2:2:end,1:4])'
Xte_labels = Vector(iris[2:2:end,5])

print("split; Performing PCA: ")

# Suppose Xtr and Xte are training and testing data matrix, with each observation in a column. We train a PCA model, allowing up to 3 dimensions:
M = fit(PCA, Xtr; maxoutdim=3)
println(M)

# Then, apply PCA model to the testing set
Yte = predict(M, Xte)
println(Yte)

# And, reconstruct testing observations (approximately) to the original space
Xr = reconstruct(M, Yte)
println(Xr)

# Now, we group results by testing set labels for color coding and visualize first 3 principal components in 3D plot
println("Plotting fn:")
setosa = Yte[:,Xte_labels.=="setosa"]
versicolor = Yte[:,Xte_labels.=="versicolor"]
virginica = Yte[:,Xte_labels.=="virginica"]

p = scatter(setosa[1,:],setosa[2,:],setosa[3,:],marker=:circle,linewidth=0)
scatter!(versicolor[1,:],versicolor[2,:],versicolor[3,:],marker=:circle,linewidth=0)
scatter!(virginica[1,:],virginica[2,:],virginica[3,:],marker=:circle,linewidth=0)
plot!(p,xlabel="PC1",ylabel="PC2",zlabel="PC3")

println("Reached end of program.")

在Linux终端通过命令julia mycode.jl运行上述代码,代码能正常执行到结束,但绘图无法显示。请问问题出在哪里,该如何解决?


问题原因与解决办法

核心原因

  1. 代码仅创建了绘图对象p,但未主动触发显示操作;
  2. Linux终端环境默认可能不支持交互式图形渲染,Plots的默认后端(如GR)无法在无GUI或未配置的终端中显示图形。

具体解决办法

1. 主动触发绘图显示

在代码末尾添加显示绘图的命令,让程序明确执行显示操作:

display(p)

如果是带桌面环境的Linux系统,终端能调用图形服务的话,添加后即可弹出绘图窗口。

2. 保存绘图为文件(无GUI环境首选)

如果运行环境没有图形界面(如远程服务器),直接将绘图保存为图片或HTML文件:

  • 保存为PNG图片:
    savefig(p, "pca_iris_3d.png")
    
    运行后当前目录会生成图片文件,可下载到本地查看。
  • 保存为交互式HTML(需要PlotlyJS后端):
    先安装后端:
    ] add PlotlyJS
    
    然后修改代码开头,切换后端并保存:
    using Plots
    plotlyjs() # 切换到PlotlyJS后端
    # ... 其余代码不变 ...
    savefig(p, "pca_iris_plot.html")
    
    生成的HTML文件可在任意浏览器中打开查看交互式3D图。

3. 配置终端图形环境(桌面Linux系统)

如果是带桌面的Linux系统仍无法显示,检查以下两点:

  • 确保系统安装了图形依赖库,比如Debian/Ubuntu系安装:
    sudo apt install libgl1-mesa-glx libx11-xcb1
    
  • 确保终端能访问DISPLAY环境变量,运行代码前可先执行:
    export DISPLAY=:0
    
    再运行julia mycode.jl。

内容的提问来源于stack exchange,提问作者rnso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:27:24