插件窝 干货文章 Python终端界面下如何绘制折线图?

Python终端界面下如何绘制折线图?

线图 终端 绘制 图表 435    来源:    2025-03-15

在Python终端界面下绘制折线图可以使用一些基于文本的绘图库,如 matplotlib 的文本模式、termplotlibasciichart。这些库可以在终端中以文本形式绘制简单的图表。

1. 使用 matplotlib 的文本模式

matplotlib 是一个强大的绘图库,虽然它通常用于图形界面,但它也支持在终端中输出文本形式的图表。

import matplotlib.pyplot as plt
import numpy as np

# 生成一些数据
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 绘制折线图
plt.plot(x, y)

# 在终端中显示文本形式的图表
plt.show()

在终端中运行上述代码时,matplotlib 会尝试在图形界面中显示图表。如果你希望在终端中显示文本形式的图表,可以使用 plt.textplt.figtext 来手动输出文本。

2. 使用 termplotlib

termplotlib 是一个专门用于在终端中绘制图表的库。

首先,你需要安装 termplotlib

pip install termplotlib

然后,你可以使用以下代码在终端中绘制折线图:

import termplotlib as tpl
import numpy as np

# 生成一些数据
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 创建折线图
fig = tpl.figure()
fig.plot(x, y, label="sin(x)", width=50, height=15)
fig.show()

3. 使用 asciichart

asciichart 是一个简单的库,可以在终端中以 ASCII 字符绘制折线图。

首先,安装 asciichart

pip install asciichart

然后,使用以下代码在终端中绘制折线图:

import asciichartpy as asciichart
import numpy as np

# 生成一些数据
y = np.sin(np.linspace(0, 2 * np.pi, 100))

# 绘制折线图
chart = asciichart.plot(y, {'height': 10})
print(chart)

4. 使用 plotext

plotext 是一个专门用于在终端中绘制图表的库,支持多种图表类型。

首先,安装 plotext

pip install plotext

然后,使用以下代码在终端中绘制折线图:

import plotext as plt

# 生成一些数据
x = range(100)
y = [i ** 2 for i in x]

# 绘制折线图
plt.plot(x, y)
plt.show()

总结

  • 如果你需要简单的文本图表,可以使用 asciicharttermplotlib
  • 如果你需要更复杂的图表,并且希望在终端中显示,可以使用 plotext
  • matplotlib 虽然功能强大,但在终端中显示文本图表的功能有限。

根据你的需求选择合适的库来在终端中绘制折线图。