如何通过散点图绘制一条线而没有溢出 [英] How to draw a line through a scatter graph with no overflow

查看:105
本文介绍了如何通过散点图绘制一条线而没有溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我目前正在matplotlib中绘制包含许多xy的散点图:

So I am currently plotting a scatter graph with many x and ys in matplotlib:

plt.scatter(x, y)

我想在此散点图上画一条线,穿过整个图(即击中两个边界"),我知道梯度和截距-等式y = mx +c中的mc.

I want to draw a line on this scatter graph that crosses through the whole graph (i.e hits two 'borders') I know the gradient and the intercept - m and the c in the equation y = mx +c.

我考虑过要获取曲线图的4个点(计算最小和最大散点xy s),然后从中计算直线的最小和最大坐标,然后进行绘制,但这看起来很复杂.有没有更好的方法可以做到这一点,请牢记线甚至可能不在图"内?

I have thought about acquiring the 4 points of the plot (calculating the min and max scatter x and ys) and from that calculating the min and max coords for the line and then plotting but that seems very convoluted. Is there any better way to do this bearing in mind the line may not even be 'within' the 'plot'?

散点图示例:

在图中通过视觉识别,四个边界坐标大致是:

as identified visually in the plot the four bordering coordinates are ruffly:

  • 左下方:-1,-2
  • 左上:-1,2
  • 右下:6,-2
  • 右上方6,2
  • bottom left: -1,-2
  • top left: -1,2
  • bottom right: 6,-2
  • top right 6,2

我现在需要绘制一条线,该线不得超过这些边界,但是如果它进入该线,则必须接触两个边界点.

I now have a line that I need to plot that must not exceed these boundaries but if it enters the plot must touch two of the boundary points.

因此,我可以检查x = -1时y等于什么,然后检查该值是否在-1和6之间,以及是否该线必须越过左边界,因此进行绘制,依此类推,等等.

So I could check what y equals when x = -1 and then check if that value is between -1 and 6 and if it is the line must cross the left border, so plot it, and so on and so fourth.

理想情况下,尽管我会创建从-infinity到infinity的线,然后对其进行裁剪以适合剧情.

Ideally though I would create a line from -infinity to infinity and then crop it to fit the plot.

推荐答案

您可以尝试:

import matplotlib.pyplot as plt
import numpy as np

m=3
c=-2
x1Data= np.random.normal(scale=2, loc=.4, size=25)
y1Data= np.random.normal(scale=3, loc=1.2, size=25)
x2Data= np.random.normal(scale=1, loc=3.4, size=25)
y2Data= np.random.normal(scale=.65, loc=-.2, size=25)

fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )
ax.scatter(x1Data, y1Data)
ax.scatter(x2Data, y2Data)
ylim = ax.get_ylim()
xlim = ax.get_xlim()
ax.plot( xlim, [ m * x + c for x in xlim ], 'r:' )
ax.set_ylim( ylim )
ax.set_xlim( xlim )
plt.show()

给出:

这篇关于如何通过散点图绘制一条线而没有溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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