如何用matplotlib画一条线? [英] How to draw a line with matplotlib?

查看:763
本文介绍了如何用matplotlib画一条线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到用matplotlib Python库绘制任意行的方法.它允许绘制水平和垂直线(例如,使用matplotlib.pyplot.axhlinematplotlib.pyplot.axvline),但是我看不到如何通过两个给定点(x1, y1)(x2, y2)绘制线.有办法吗?有没有简单的方法?

I cannot find a way to draw an arbitrary line with matplotlib Python library. It allows to draw horizontal and vertical lines (with matplotlib.pyplot.axhline and matplotlib.pyplot.axvline, for example), but i do not see how to draw a line through two given points (x1, y1) and (x2, y2). Is there a way? Is there a simple way?

推荐答案

我正在检查ax.axvline的工作方式,并且编写了一个类似于其构想的小函数:

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    ax.add_line(l)
    return l

因此,如果您运行以下代码,您将意识到它是如何工作的.该线将跨越整个绘图范围(与它的大小无关),并且线的创建不依赖于轴内的任何数据点,而仅依赖于您需要指定的两个固定点. /p>

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)
newline(p1,p2)
plt.show()

这篇关于如何用matplotlib画一条线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆