在Python终端下绘制类似nvtop
的折线图,可以使用一些终端绘图库。nvtop
是一个用于监控GPU使用情况的工具,它会在终端中显示实时的折线图。要在Python中实现类似的效果,可以使用blessed
、urwid
、asciimatics
等库来创建终端用户界面,并结合matplotlib
或plotext
等库来绘制折线图。
以下是一个使用plotext
库在终端中绘制折线图的简单示例:
plotext
库首先,你需要安装plotext
库。你可以通过以下命令安装:
pip install plotext
接下来,编写一个简单的Python脚本来绘制折线图:
import plotext as plt
import time
import random
# 初始化数据
x = list(range(10))
y = [random.randint(0, 100) for _ in range(10)]
# 设置标题和标签
plt.title("GPU Usage Over Time")
plt.xlabel("Time (s)")
plt.ylabel("Usage (%)")
# 绘制折线图
plt.plot(x, y, label="GPU Usage")
# 显示图例
plt.show()
# 模拟实时更新
while True:
time.sleep(1) # 每秒更新一次
y.pop(0) # 移除第一个数据点
y.append(random.randint(0, 100)) # 添加新的随机数据点
plt.clear_data() # 清除旧数据
plt.plot(x, y, label="GPU Usage") # 重新绘制
plt.show() # 显示更新后的图表
运行上述代码后,你将在终端中看到一个实时更新的折线图,类似于nvtop
的效果。
如果你需要更复杂的终端用户界面,可以考虑使用urwid
或asciimatics
库来创建更复杂的布局和交互。
matplotlib
在终端中绘图如果你更喜欢使用matplotlib
,可以通过以下方式在终端中显示图像:
pip install matplotlib
然后使用以下代码:
import matplotlib.pyplot as plt
import numpy as np
import time
# 初始化数据
x = np.arange(10)
y = np.random.randint(0, 100, size=10)
# 创建图形
plt.ion() # 开启交互模式
fig, ax = plt.subplots()
line, = ax.plot(x, y)
# 设置标题和标签
ax.set_title("GPU Usage Over Time")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Usage (%)")
# 模拟实时更新
while True:
time.sleep(1) # 每秒更新一次
y = np.roll(y, -1) # 滚动数据
y[-1] = np.random.randint(0, 100) # 更新最后一个数据点
line.set_ydata(y) # 更新折线图数据
plt.draw() # 重新绘制
plt.pause(0.1) # 短暂暂停以更新图形
在Python终端中绘制类似nvtop
的折线图,可以使用plotext
或matplotlib
等库。plotext
更适合直接在终端中显示图形,而matplotlib
则更适合在图形界面中显示。根据你的需求选择合适的工具。