在python中使用Line2D绘制线

2024-04-29 15:56:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有数据:

x = [10,24,23,23,3]
y = [12,2,3,4,2]

我想用

matplotlib.lines.Line2D(xdata, ydata)

我用

import matplotlib.lines

matplotlib.lines.Line2D(x, y)

但我该怎么显示这条线呢?


Tags: 数据importmatplotliblinesxdataydataline2d线呢
2条回答

应将线添加到绘图中,然后显示:

In [13]: import matplotlib.pyplot as plt

In [15]: from matplotlib.lines import Line2D      

In [16]: fig = plt.figure()

In [17]: ax = fig.add_subplot(111)

In [18]: x = [10,24,23,23,3]

In [19]: y = [12,2,3,4,2]

In [20]: line = Line2D(x, y)

In [21]: ax.add_line(line)
Out[21]: <matplotlib.lines.Line2D at 0x7f4c10732f60>

In [22]: ax.set_xlim(min(x), max(x))
Out[22]: (3, 24)

In [23]: ax.set_ylim(min(y), max(y))
Out[23]: (2, 12)

In [24]: plt.show()

结果是:

enter image description here

更常见的方法(不完全是提问者所要求的)是使用plot接口。这涉及到幕后的Line2D。

>>> x = [10,24,23,23,3]
>>> y = [12,2,3,4,2]
>>> import matplotlib.pyplot as plt
>>> plt.plot(x,y)
[<matplotlib.lines.Line2D object at 0x7f407c1a8ef0>]
>>> plt.show()

相关问题 更多 >