如何在终端中绘制图表?
How to plot a chart in the terminal?
我正在研究 ML/Theano,最近发现了这个脚本:https://gist.github.com/notmatthancock/68d52af2e8cde7fbff1c9225b2790a7f 玩起来很酷。和所有 ML 研究人员一样,我最近升级到服务器,虽然它更强大,但也给我带来了问题。
脚本很长,但以这段代码结尾:
def plot_stuff(inputs, outputs, losses, net_func, n_hidden):
fig,axes = plt.subplots(1,2,figsize=(12,6))
axes[0].plot(np.arange(losses.shape[0])+1, losses)
axes[0].set_xlabel('iteration')
axes[0].set_ylabel('loss')
axes[0].set_xscale('log')
axes[0].set_yscale('log')
x,y = np.mgrid[inputs[:,0].min():inputs[:,0].max():51j, inputs[:,1].min():inputs[:,1].max():51j]
z = net_func( np.c_[x.flatten(), y.flatten()] ).reshape(x.shape)
axes[1].contourf(x,y,z, cmap=plt.cm.RdBu, alpha=0.6)
axes[1].plot(inputs[outputs==0,0], inputs[outputs==0,1], 'or')
axes[1].plot(inputs[outputs==1,0], inputs[outputs==1,1], 'sb')
axes[1].set_title('Percent missclassified: %0.2f%%' % (((net_func(inputs)>0.5) != outputs.astype(np.bool)).mean()*100))
fig.suptitle('Shallow net with %d hidden units'%n_hidden)
plt.show()
if __name__=='__main__':
n_hidden = 40
inputs, outputs = gen_data(n_samples_per_class=100)
losses, net_func = train_neural_network(inputs=inputs, outputs=outputs, n_hidden=n_hidden, n_iters=int(2000), learning_rate=0.1)
plot_stuff(inputs, outputs, losses, net_func, n_hidden)
生成此图表的对象:
当我尝试在服务器上 运行 它时,服务器没有屏幕只有命令行,我可以预见到这个错误:
fedora@ip-173-33-18-911:~/scripting/spiral$ python spiral.py
Iteration 2000 / 2000, Loss: 0.172083
Traceback (most recent call last):
File "spiral.py", line 133, in <module>
plot_stuff(inputs, outputs, losses, net_func, n_hidden)
File "spiral.py", line 110, in plot_stuff
fig,axes = plt.subplots(1,2,figsize=(12,6))
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 1046, in subplots
fig = figure(**fig_kw)
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 423, in figure
**kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 79, in new_figure_manager
return new_figure_manager_given_figure(num, figure)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 87, in new_figure_manager_given_figure
window = Tk.Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1767, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
是否有way/method/function在命令行中显示图表和图形?
这里有几个选项:
导出为图像或 PDF。在这里找到的信息:http://matplotlib.org/faq/howto_faq.html 这里的关键信息如下:
# do this before importing pylab or pyplot
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])
fig.savefig('test.png')
如果你的服务器支持X11转发(或者如果你可以enable/installX11转发),你可以通过设置你的显示SSH进入服务器。来自 linux、运行:
DISPLAY=:0.0 ssh -Y <server ip>
这会将您的计算机设置为将服务器的任何显示输出转发到您的 PC。如果你是 运行ning Windows,你可以使用 MobaXterm 来简化它,或者自己配置一个 X11 客户端。 Mac如果我没记错的话同样简单
如果要弹出外部 window 图表,运行 图表,然后
>>> matplotlib.pyplot.show(block=True)
这将在单独的 window 中弹出图表。
如果您在此调用之前多次调用 plot()
,它将随相应的图表弹出等量的 windows。控制returns到Python只有关闭所有弹出的图表windows.
我喜欢把它包装在一个小辅助函数中,像这样:
def show():
return matplotlib.pyplot.show(block=True)
然后,每当我想查看任何尚未显示的图时,我只需调用 show()
。
我创建了一个名为 termplot
的小程序包,它可以根据列表创建垂直条形图。
pip install termplot
import termplot
termplot.plot([1,2,3,4,-5,5,-4,-1,0,-10,-4,-2,3,5,8,10,12,10,8,7,6,5,4,3,2,1])
在我看来 terminalplot 比 @William234234 建议的包更完整可能是一个很好的解决方案。
用法示例:
import terminalplot as tp
import numpy as np
from math import sin, pi
x=np.linspace(0,2*pi,100);
y=[sin(m)+m for m in x];
tp.plot(list(x),y)
termplotlib(我的一个小项目)在这里可能会派上用场。使用
安装
pip install termplotlib
并生成像
这样的终端图
import termplotlib as tpl
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x) + x
fig = tpl.figure()
fig.plot(x, y, width=60, height=20)
fig.show()
7 +---------------------------------------------------+
| |
6 | ** |
| ** |
| ** |
5 | ** |
| *** |
4 | **** |
| ***** |
3 | ***************** |
| **** |
2 | *** |
| *** |
| *** |
1 | ** |
|** |
0 +---------------------------------------------------+
0 1 2 3 4 5 6 7
检查允许直接在终端上绘制数据的包 plotext。它非常直观,因为它的语法非常类似于 matplotlib.
这是一个基本示例:
import plotext as plt
y = plt.sin() # sinusoidal signal
plt.scatter(y)
plt.title("Scatter Plot")
plt.show()
您还可以绘制 条形图:
此处显示了绘制连续数据流的示例:
可以安装和
pip install plotext
或与:
pip install "plotext[image]"
将 plotext 与图像一起使用。
可以在终端和终端仿真器中绘制光栅图像:
import matplotlib
matplotlib.use('module://matplotlib-sixel')
from pylab import *
plt.plot(sin(arange(100) / 10))
show()
此特定示例使用 matplotlib-sixel, a library that uses Xterm emulating a Sixel compatible terminal and ImageTrick. Similar technology could be implemented in the Linux terminal (through the Framebuffer) or emulators (kitty or iTerm2). The FOSS community has given great solutions in the last years (like libsixel).
另一种选择是使用 X11 forwarding or using a Sixel-based printer like lsix。但是所有这些选项都会发生在 Python shell 本身之外。
当然,在服务器中 运行 a Jupyter Notebook 可能比尝试在终端中强行插入图像更好。这可能不值得。
您可能有兴趣查看 uniplot,这是我专门为 ML/data 科学管道编写的 Python 库。可能正是您要找的。
与其他终端绘图仪相比,具有 4 倍的分辨率,这要归功于 Unicode。
我还没有像你那样做高级图形,但对于线条、散点图和直方图,它工作得很好。
我正在研究 ML/Theano,最近发现了这个脚本:https://gist.github.com/notmatthancock/68d52af2e8cde7fbff1c9225b2790a7f 玩起来很酷。和所有 ML 研究人员一样,我最近升级到服务器,虽然它更强大,但也给我带来了问题。
脚本很长,但以这段代码结尾:
def plot_stuff(inputs, outputs, losses, net_func, n_hidden):
fig,axes = plt.subplots(1,2,figsize=(12,6))
axes[0].plot(np.arange(losses.shape[0])+1, losses)
axes[0].set_xlabel('iteration')
axes[0].set_ylabel('loss')
axes[0].set_xscale('log')
axes[0].set_yscale('log')
x,y = np.mgrid[inputs[:,0].min():inputs[:,0].max():51j, inputs[:,1].min():inputs[:,1].max():51j]
z = net_func( np.c_[x.flatten(), y.flatten()] ).reshape(x.shape)
axes[1].contourf(x,y,z, cmap=plt.cm.RdBu, alpha=0.6)
axes[1].plot(inputs[outputs==0,0], inputs[outputs==0,1], 'or')
axes[1].plot(inputs[outputs==1,0], inputs[outputs==1,1], 'sb')
axes[1].set_title('Percent missclassified: %0.2f%%' % (((net_func(inputs)>0.5) != outputs.astype(np.bool)).mean()*100))
fig.suptitle('Shallow net with %d hidden units'%n_hidden)
plt.show()
if __name__=='__main__':
n_hidden = 40
inputs, outputs = gen_data(n_samples_per_class=100)
losses, net_func = train_neural_network(inputs=inputs, outputs=outputs, n_hidden=n_hidden, n_iters=int(2000), learning_rate=0.1)
plot_stuff(inputs, outputs, losses, net_func, n_hidden)
生成此图表的对象:
fedora@ip-173-33-18-911:~/scripting/spiral$ python spiral.py
Iteration 2000 / 2000, Loss: 0.172083
Traceback (most recent call last):
File "spiral.py", line 133, in <module>
plot_stuff(inputs, outputs, losses, net_func, n_hidden)
File "spiral.py", line 110, in plot_stuff
fig,axes = plt.subplots(1,2,figsize=(12,6))
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 1046, in subplots
fig = figure(**fig_kw)
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 423, in figure
**kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 79, in new_figure_manager
return new_figure_manager_given_figure(num, figure)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 87, in new_figure_manager_given_figure
window = Tk.Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1767, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
是否有way/method/function在命令行中显示图表和图形?
这里有几个选项:
导出为图像或 PDF。在这里找到的信息:http://matplotlib.org/faq/howto_faq.html 这里的关键信息如下:
# do this before importing pylab or pyplot import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3]) fig.savefig('test.png')
如果你的服务器支持X11转发(或者如果你可以enable/installX11转发),你可以通过设置你的显示SSH进入服务器。来自 linux、运行:
DISPLAY=:0.0 ssh -Y <server ip>
这会将您的计算机设置为将服务器的任何显示输出转发到您的 PC。如果你是 运行ning Windows,你可以使用 MobaXterm 来简化它,或者自己配置一个 X11 客户端。 Mac如果我没记错的话同样简单
如果要弹出外部 window 图表,运行 图表,然后
>>> matplotlib.pyplot.show(block=True)
这将在单独的 window 中弹出图表。
如果您在此调用之前多次调用 plot()
,它将随相应的图表弹出等量的 windows。控制returns到Python只有关闭所有弹出的图表windows.
我喜欢把它包装在一个小辅助函数中,像这样:
def show():
return matplotlib.pyplot.show(block=True)
然后,每当我想查看任何尚未显示的图时,我只需调用 show()
。
我创建了一个名为 termplot
的小程序包,它可以根据列表创建垂直条形图。
pip install termplot
import termplot
termplot.plot([1,2,3,4,-5,5,-4,-1,0,-10,-4,-2,3,5,8,10,12,10,8,7,6,5,4,3,2,1])
在我看来 terminalplot 比 @William234234 建议的包更完整可能是一个很好的解决方案。
用法示例:
import terminalplot as tp
import numpy as np
from math import sin, pi
x=np.linspace(0,2*pi,100);
y=[sin(m)+m for m in x];
tp.plot(list(x),y)
termplotlib(我的一个小项目)在这里可能会派上用场。使用
安装pip install termplotlib
并生成像
这样的终端图import termplotlib as tpl
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x) + x
fig = tpl.figure()
fig.plot(x, y, width=60, height=20)
fig.show()
7 +---------------------------------------------------+
| |
6 | ** |
| ** |
| ** |
5 | ** |
| *** |
4 | **** |
| ***** |
3 | ***************** |
| **** |
2 | *** |
| *** |
| *** |
1 | ** |
|** |
0 +---------------------------------------------------+
0 1 2 3 4 5 6 7
检查允许直接在终端上绘制数据的包 plotext。它非常直观,因为它的语法非常类似于 matplotlib.
这是一个基本示例:
import plotext as plt
y = plt.sin() # sinusoidal signal
plt.scatter(y)
plt.title("Scatter Plot")
plt.show()
您还可以绘制 条形图:
此处显示了绘制连续数据流的示例:
可以安装和
pip install plotext
或与:
pip install "plotext[image]"
将 plotext 与图像一起使用。
可以在终端和终端仿真器中绘制光栅图像:
import matplotlib
matplotlib.use('module://matplotlib-sixel')
from pylab import *
plt.plot(sin(arange(100) / 10))
show()
此特定示例使用 matplotlib-sixel, a library that uses Xterm emulating a Sixel compatible terminal and ImageTrick. Similar technology could be implemented in the Linux terminal (through the Framebuffer) or emulators (kitty or iTerm2). The FOSS community has given great solutions in the last years (like libsixel).
另一种选择是使用 X11 forwarding or using a Sixel-based printer like lsix。但是所有这些选项都会发生在 Python shell 本身之外。
当然,在服务器中 运行 a Jupyter Notebook 可能比尝试在终端中强行插入图像更好。这可能不值得。
您可能有兴趣查看 uniplot,这是我专门为 ML/data 科学管道编写的 Python 库。可能正是您要找的。
与其他终端绘图仪相比,具有 4 倍的分辨率,这要归功于 Unicode。
我还没有像你那样做高级图形,但对于线条、散点图和直方图,它工作得很好。