在ipython notebook中的matplotlib图中添加任意一行 [英] Adding an arbitrary line to a matplotlib plot in ipython notebook

查看:380
本文介绍了在ipython notebook中的matplotlib图中添加任意一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python / matplotlib都很陌生,并通过ipython笔记本使用它。我正在尝试向现有图形添加一些注释线,我无法弄清楚如何在图形上渲染线条。因此,例如,如果我绘制以下内容:

I'm rather new to both python/matplotlib and using it through the ipython notebook. I'm trying to add some annotation lines to an existing graph and I can't figure out how to render the lines on a graph. So, for example, if I plot the following:

import numpy as np
np.random.seed(5)
x = arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
p =  plot(x, y, "o")

我得到以下图表:

那我该如何添加一个垂直线从(70,100)到(70,250)?从(70,100)到(90,200)的对角线怎么样?

So how would I add a vertical line from (70,100) up to (70,250)? What about a diagonal line from (70,100) to (90,200)?

我用 Line2D()只会导致混淆。在 R 中,我只使用segments()函数来添加线段。在 matplotlib 中是否存在等价物?

I've tried a few things with Line2D() resulting in nothing but confusion on my part. In R I would simply use the segments() function which would add line segments. Is there an equivalent in matplotlib?

推荐答案

你可以直接绘制通过输入 plot 命令以及相应的数据(段的边界)来获得所需的行:

You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments):

plot([x1,x2],[y1,y2],color ='k',linestyle =' - ',linewidth = 2)

(当然你可以选择颜色,线宽,线条样式等)。

(of course you can choose the color, line width, line style, etc.)

来自你的例子:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)

# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()

这篇关于在ipython notebook中的matplotlib图中添加任意一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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